Java将UTC时间戳转换为本地DateTime

我知道有很多关于将UTC时间/日期转换为当地时间的回复post,但没有帮助我弄清楚我的问题是什么。 我的问题是:通过UTC时间戳,我如何获得本地DateTime? 这就是我现在所拥有的,但这只是将时间戳转换为DateTime格式。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getDefault()); sdf.format(new Date(timestamp * 1000)); 

编辑:我在云上保存UTC时间戳,以便每个设备(Android / iOS)都可以查询并转换为它的时区。

试试这个和我一起工作

 public String getDateCurrentTimeZone(long timestamp) { try{ Calendar calendar = Calendar.getInstance(); TimeZone tz = TimeZone.getDefault(); calendar.setTimeInMillis(timestamp * 1000); calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis())); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date currenTimeZone = (Date) calendar.getTime(); return sdf.format(currenTimeZone); }catch (Exception e) { } return ""; } 

你可以试试这个

  String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss az" ; final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String dateTimeString = sdf.format(new Date()); System.out.println(dateTimeString); // current UTC time long timeStamp=sdf.parse(dateTimeString).getTime(); //current UTC time in milisec Calendar cal = Calendar.getInstance(); cal.setTime(new Date(timeStamp)); cal.add(Calendar.HOUR_OF_DAY, 5); cal.add(Calendar.MINUTE, 30); System.out.println(sdf.format(cal.getTime())); // time relevant to UTC+5.30 

你可以使用Joda时间将本地转换为UTC,反之亦然,例如本地转换为UTC

 DateTime dateTimeNew = new DateTime(date.getTime(), DateTimeZone.forID("Asia/Calcutta")); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String datetimeString = dateTimeNew.toString("yyyy-MM-dd HH:mm:ss"); long milis = 0; try { milis = simpleDateFormat.parse(datetimeString).getTime(); } catch (ParseException e) { e.printStackTrace(); }