java - 无法将 UTC 转换为本地时间

标签 java datetime

我正在编写Java代码。我能够将本地时间转换为UTC。但是当我想将其转换回本地时间时,我遇到了问题。我正在执行的步骤-

  1. 获取当前的毫秒数。(完成)
  2. 将当前毫秒(millisSinceEpoch) 转换为当前本地时间。(DONE)
  3. 将当前毫秒(millisSinceEpoch) 转换为 UTC 时间。(完成)
  4. 将 UTC 时间转换为 UTC 毫秒。(完成)
  5. 将 UTC 毫秒转换为 UTC 时间。(完成)
  6. 将 UTC 毫秒转换为本地时间(IST)(这里面临问题.....在这里获取相同的 UTC 时间。为什么它不转换为本地时间?)。有一个答案,其中多个日期创建了对象,但这里我没有创建多个日期对象并且仅在毫秒上工作。我的代码-

    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.time.Instant;
    import java.time.ZonedDateTime;
    import java.util.Date;
    import java.util.TimeZone;
    public class TimeApiClass {
    public static void main(String args[]) throws ParseException {
    ZonedDateTime currentZone = ZonedDateTime.now();
    
    //Getting milliseconds of the present
    Instant instant=currentZone.toInstant();
    long millisSinceEpoch=instant.toEpochMilli();
    System.out.println("Not Converted to UTC-(Milliseconds-in local)");
    System.out.println(millisSinceEpoch);                                //Output1->1579788244731
    
    //Converting present milliseconds(millisSinceEpoch) to present local time
    SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS ");
    String str3=sdf3.format(new Date(millisSinceEpoch));
    System.out.println("Local Time-Not Converted to UTC-(Present local time)");
    System.out.println(str3);                                           //2020/01/23 19:34:04.731
    
    
    
    //Converting present milliseconds(millisSinceEpoch) to UTC time
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS ");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String str=sdf.format(new Date(millisSinceEpoch));
    System.out.println("UTC time-Local time Converted to UTC(unrequired time format)-");
    System.out.println(str);// str contains 2020/01/22 13:22:55 UTC     //Output3 ->2020/01/23 14:04:04.731
    
    System.out.println("-----------------------------------------------------------------------------------------");
    
    
    //Converting UTC time to UTC milliseconds
    String myDate = str;  // myDate and str contains 2020/01/22 10:08:42
    SimpleDateFormat sdff = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS ");
    Date date = sdff.parse(myDate);
    long millis = date.getTime();
    System.out.println("Converted to milliseconds(Now its in required format in UTC milliseconds)");
    System.out.println(millis);                                       //Output4 ->1579749867000
    
    
    //Convert UTC milliseconds to UTC Time
    DateFormat simple = new SimpleDateFormat(" yyyy/MM/dd HH:mm:ss.SSS");
    Date result=new Date(millis);
    System.out.println("Converting UTC milliseconds back to date/time format-");
    System.out.println(simple.format(result));
    
    
    //Convert UTC milliseconds to local time(IST)
    Date dateee=new Date(millis);         //Facing the problem here.....Getting the same UTC time here.Why is it not converting to Local time?
    DateFormat format=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
    format.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    System.out.println("lllllllllllllllllllllllll");
    System.out.println(format.format(dateee));
    
    
    
    
    //Converting UTC time to IST time
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS ");
    sdf2.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    String istTime=sdf2.format(new Date(millis));
    System.out.println("Now converting UTC millis to IST format->");
    System.out.println(istTime);                                     //Output5 ->2020/01/23 08:54:27 IST
    
    
    //Converting IST time to milliseconds,here I am facing the problem.My output has to give the local milliseconds as I am passing ISTtime here,but its giving me UTC milliseconds,Which I dont want.
    Date date66=sdf2.parse(istTime);
    long finalMillis=date66.getTime();
    System.out.println("Now converting IST to IST milliseconds:");
    System.out.println(finalMillis);                               //Output6 ->1579749867000
    

    } } //1579613838087

最佳答案

tl;博士

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

<小时/>

不建议您使用 java.util.SimpleDateFormat 进行日期和时间操作,并且您的代码显示部分使用 java.time,这意味着您可以只需完全切换到 java.time 即可。对于格式化,请使用java.time.format.DateTimeFormatter

请参阅此示例:

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));
}

输出类似于:

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]

关于java - 无法将 UTC 转换为本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59882082/

相关文章:

java - codingbat 递归练习

java - 如何在 JUnit @Parameters 中将 null 作为参数传递?

python - 将毫秒转换为小时、分钟和秒 python

java - 类 "com.android.okhttp.HttpHandler"的定义在哪里?

java - Java 中的 'ambiguous type' 错误是什么?

php - 使用 MongoDate 与 UTCDateTime 进行查询

MySQL - BETWEEN 子句无法与 DATETIME 一起正常工作

c# - 使用 DateTime.ParseExact C# 未将字符串识别为有效的 DateTime

node.js - 无法在 Lambda 中创建具有 UTC 旁边时区的日期对象

java - Hibernate 在 1 天后无法执行查询