首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法将协调世界时转换为当地时间

问无法将协调世界时转换为当地时间
EN

Stack Overflow用户
提问于 2020-01-23 15:32:36
回答 2查看 562关注 0票数 0

我正在编写一个Java代码,我能够将本地时间转换为UTC.But,当我想将它转换回我正在执行的本地time.The步骤时,我将面临这个问题-

  1. 得到毫秒的现在。(完成)
  2. 将当前毫秒(MillisSinceEpoch)转换为当前本地时间。(已完成)
  3. 将当前毫秒(MillisSinceEpoch)转换为UTC时间。(已完成)
  4. 将UTC时间转换为UTC毫秒。(已完成)
  5. 将UTC毫秒转换为UTC时间。(已完成)
  6. 将UTC毫秒转换为本地时间(面对问题here.....Getting同样的UTC时间here.Why,它不是转换为本地时间吗?).There是一个创建多个日期对象的答案,但这里我不是创建多个日期对象,而是只处理milliseconds.My代码- 导入java.text.DateFormat;导入java.text.ParseException;导入java.text.SimpleDateFormat;导入java.time.Instant;导入java.time.ZonedDateTime;导入java.util.Date;导入java.util.TimeZone;公共类TimeApiClass {公共静态无效main(String args[])抛出ParseException { ZonedDateTime currentZone = ZonedDateTime.now();//获取当前Instant instant=currentZone.toInstant()的毫秒;long millisSinceEpoch=instant.toEpochMilli();System.out.println(“未转换为UTC-(毫秒-在本地)”);System.out.println(millisSinceEpoch=instant.toEpochMilli);//输出1->1579788244731//将当前毫秒(MillisSinceEpoch)转换为当前本地时间SimpleDateFormat sdf3 =新SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS ");字符串str3=sdf3.format(新日期(MillisSinceEpoch));System.out.println(“本地时间-未转换为UTC-(当前本地时间)”);System.out.println(str3);//2020/01/23 19:34:04.731 /将当前毫秒(MillisSinceEpoch)转换为UTC时间SimpleDateFormat sdf =新SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS ");sdf.setTimeZone(“UTC”);String str=sdf.format(新日期(MillisSinceEpoch));System.out.println("UTC时间-当地时间转换为UTC(不需要的时间格式)-“);System.out.println(str);// str包含2020/01/22 13:22:55 UTC //Output3 ->2020/01/23 14:04:04.731 System.out.println("-----------------------------------------------------------------------------------------");//将UTC时间转换为UTC毫秒字符串myDate = str;// myDate和str包含2020/01/22 10:08:42 SimpleDateFormat sdff =新SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS ");Date = sdff.parse(myDate);long millis = date.getTime();System.out.println(“转换为毫秒(以UTC毫秒表示)”;System.out.println(millis);//Output4 4 ->1579749867000 //将UTC毫秒转换为UTC时间DateFormat simple =新SimpleDateFormat(“yyyy/MM/dd HH:mm:ss.SSS");Date result=new Date(millis);System.out.println(”将UTC毫秒转换回日期/时间格式-“);System.out.println(simple.format(结果);//将UTC毫秒转换为本地时间的日期dateee=new日期(Millis);//面对这个问题,here.....Getting,同样的UTC时间,here.Why,它不是转换成本地时间吗?format.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));System.out.println("lllllllllllllllllllllllll");format=new SimpleDateFormat (yyyy/MM/dd HH:mm:ss.SSS );DateFormat System.out.println(日期日期);//将UTC时间转换为IST time SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");sdf2.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));String istTime=sdf2.format(新日期(Millis));System.out.println(“现在将UTC转换为IST格式->”);System.out.println( ISTtime );//Output5 ->2020/01/23 08:54:27 IST //将IST时间转换为毫秒,这里我面临的problem.My输出必须在这里传递ISTtime时给出本地毫秒,但它给我UTC毫秒,我不想要。Date date66=sdf2.parse(istTime);long finalMillis=date66.getTime();System.out.println(“现在将IST转换为IST毫秒:”);System.out.println(finalMillis);//Output6 6 ->1579749867000 } //1579613838087
EN

回答 2

Stack Overflow用户

发布于 2020-01-23 15:46:29

tl;dr

通过ZonedDateTime将ZonedDateTime.withZoneSameInstant(ZoneId)转换为不同的时区

我们不建议您在日期和时间上使用java.util.SimpleDateFormat,而且您的代码显示了部分使用java.time,这意味着您可以完全切换到java.time。要格式化,请使用java.time.format.DateTimeFormatter。

参见此示例:

代码语言:javascript
复制
public static void main(String[] args) {
    // get the current instant
    Instant instant = Instant.now();
    // and convert it to a datetime object representing date and time in UTC
    ZonedDateTime ofInstant = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC"));
    // print it
    System.out.println("Now from Instant in UTC:\t"
            + ofInstant.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));

    // you can have a shorter way: current moment in your system's time zone
    ZonedDateTime nowHere = ZonedDateTime.now();
    // or in UTC
    ZonedDateTime utcNow = ZonedDateTime.now(ZoneId.of("UTC"));

    // print them both
    System.out.println("Now in my (system's) time zone:\t"
            + nowHere.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    System.out.println("Now in UTC:\t\t\t"
            + utcNow.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));

    // then format the UTC datetime back to the one your system has
    ZonedDateTime backFromUtc = utcNow.withZoneSameInstant(ZoneId.systemDefault());
    // and print that one, too
    System.out.println("Back from UTC:\t\t\t"
            + backFromUtc.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}

输出类似于:

代码语言:javascript
复制
Now from Instant in UTC:        2020-01-23T15:44:11.921Z[UTC]
Now in my (system's) time zone: 2020-01-23T16:44:12.091+01:00[Europe/Berlin]
Now in UTC:                     2020-01-23T15:44:12.091Z[UTC]
Back from UTC:                  2020-01-23T16:50:52.194+01:00[Europe/Berlin]
票数 3
EN

Stack Overflow用户

发布于 2020-01-23 18:28:55

为什么它不转换为当地时间?

出现问题的地方是:字符串myDate在UTC中,但是(1)字符串中没有UTC的指示,(2)您正在使用格式化程序sdff解析它,但是此格式化程序不使用UTC (它使用的是默认时区印度标准时间)。因此,您从解析中得到了错误的结果。

可能还有另一个误解:无论时区如何,时代都是一个特定的时间点。因此,在所有时区中,从纪元开始的毫秒都是相同的。因此,问题的第一个迹象可能是当程序打印两个不同的毫秒值时。如果毫秒值应该表示相同的时间点,那么两次都应该看到相同的值。

所有这些都表明,deHaar在另一个答案中是正确的,即您应该远离所有的DateFormat、SimpleDateFormat、Date和TimeZone。所有这些课程的设计都很糟糕,而且已经过时了。我认为您对上述类的使用对使代码变得比所需的更复杂做出了很大贡献。

编辑:

所以你告诉我不要使用DateFormat,SimpleDateFormat和TimeZone.So,你能建议我应该使用哪一门课吗?

在使用Instant和来自java.time的ZonedDateTime (现代java.time和time )时,您已经走上了很好的道路。这个API提供了您需要的所有功能,并且使用起来更好,所以我建议您坚持使用它。您可能会发现有用的其他java.time类包括ZoneId (而不是TimeZone)和DateTimeFormatter (而不是SimpleDateFormat和DateFormat)。有关更多信息,请参见教程和/或文档。稍后我会在底部添加链接。

若要将UTC字符串解析为自时代以来的毫秒,请执行以下操作:

代码语言:javascript
复制
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss.SSS");
    String utcString = "2020/01/22 13:22:55.731";
    long millisSinceEpoch = LocalDateTime.parse(utcString, formatter)
            .atOffset(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();
    System.out.println(millisSinceEpoch);

1579699375731

或者如果你真正的目标是把它转换成印度的当地时间:

代码语言:javascript
复制
    ZoneId indiaStandardTime = ZoneId.of("Asia/Kolkata");
    ZonedDateTime timeInIndia = LocalDateTime.parse(utcString, formatter)
            .atOffset(ZoneOffset.UTC)
            .atZoneSameInstant(indiaStandardTime);
    System.out.println(timeInIndia);

2020年-01-22T18:52:55.731+05:30亚洲/加尔各答

我首先告诉Java在UTC中解释字符串,然后将它转换为IST。

链接

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59882082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档