简体   繁体   English

Java时区格式问题

[英]Java time zone format issue

The saved time in the application is in UTC. 应用程序中保存的时间以UTC为单位。 The users of the application are in different timezones, such as PST, IST etc. 应用程序的用户位于不同的时区,如PST,IST等。

My issue is very similar to the one in this post . 我的问题是非常相似的一个在这个岗位 I tried implementing a solution provided there, but it does not seem to be working for me: 我尝试在那里实现一个解决方案,但它似乎对我不起作用:

Calendar calendar = Calendar.getInstance();
calendar.setTime(history.getCreatedTimestamp());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));

//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));

I suggest you to use Java 8 classes ( SimpleDateFormat and Calendar are trouble , avoid them if possible): 我建议你使用Java 8类( SimpleDateFormatCalendar 很麻烦 ,如果可能的话,尽量避免使用它们):

long timestamp = history.getCreatedTimestamp();
// create Instant from timestamp value
Instant instant = Instant.ofEpochMilli(timestamp);

// formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

// convert to UTC
System.out.println(formatter.format(instant.atZone(ZoneOffset.UTC)));

// convert to another timezone
System.out.println(formatter.format(instant.atZone(ZoneId.of("America/Los_Angeles"))));

// convert to JVM default timezone
System.out.println(formatter.format(instant.atZone(ZoneId.systemDefault())));

Unfortunately, short zone names like PST and IST are ambiguous (check this list ), so you need to translate them to IANA's names (which are the standard used by Java, such as America/Los_Angeles or Europe/London ). 不幸的是,像PST和IST这样的短区域名称含糊不清(查看此列表 ),因此您需要将它们翻译成IANA的名称 (这是Java使用的标准,例如America/Los_AngelesEurope/London )。

More about timezones: https://codeofmatt.com/2015/02/07/what-is-a-time-zone 有关时区的更多信息: https//codeofmatt.com/2015/02/07/what-is-a-time-zone

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM