convert date and time in any timezone to UTC zone

前端 未结 2 873
情深已故
情深已故 2020-12-17 23:47
  • this is my date \" 15-05-2014 00:00:00 \"

  • how to convert IST to UTC i.e( to 14-05-2014 18:30:00)

  • based on from timezone to UTC timezo
2条回答
  •  悲哀的现实
    2020-12-18 00:21

    tl;dr

    LocalDateTime.parse( 
        "15-05-2014 00:00:00" , 
        DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" ) 
    )
    .atZone( ZoneId.of( "Asia/Kolkata" ) )
    .toInstant()
    

    java.time

    The Answer by Meno Hochschild is correct but shows classes that are now outdated.

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" ) ;
    LocalDateTime ldt = LocalDateTime.parse( "15-05-2014 00:00:00" , f ) ;
    

    ldt.toString(): 2014-05-15T00:00

    Apparently you are certain that string represents a moment in India time. Tip: You should have included the zone or offset in that string. Even better, use standard ISO 8601 formats.

    Assign the India time zone.

    ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
    ZonedDateTime zdt = ldt.atZone( z ) ;
    

    zdt.toString(): 2014-05-15T00:00+05:30[Asia/Kolkata]

    To see the same moment, the same point on the timeline, through the wall-clock time of UTC, extract an Instant.

    Instant instant = zdt.toInstant() ;
    

    instant.toString(): 2014-05-14T18:30:00Z


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.

    Where to obtain the java.time classes?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

提交回复
热议问题