How do I get a UTC Timestamp from Calendar?

前端 未结 4 572
栀梦
栀梦 2021-02-07 19:55

In Java when I use Calendar.getInstance(); I get a Calendar object for the current Timezone. But java.sql.Timestamp is usually stored in U

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-07 20:04

    tl;dr

    Instant.now() 
    

    Avoid legacy date-time classes

    You are using troublesome old date-time classes now supplanted by the java.time classes. No need to be using DateFormat, Calendar, or Timestamp.

    If you must interopt with a Calendar from old code not yet updated to java.time, convert using new methods added to the old classes. Extract an obsolete java.util.Date, and convert to Instant.

    Instant instant = myCal.getTime().toInstant() ;
    

    Using java.time

    Get the current moment as an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

    Instant instant = Instant.now() ;
    

    2017-02-17T03:29:15.725Z

    Database

    With JDBC 4.2 and later, you can directly exchange a Instant object with your database. So no need for the obsolete java.sql.Timestamp.

    myPreparedStatement.setObject( … , instant ) ;
    

    And retrieval:

    Instant instant = myResultSet.getObject( … , Instant.class ) ;
    

    Count from epoch

    Apparently you want a number of milliseconds since the epoch reference date of 1970-01-01T00:00:00Z. You can extract that number from an Instant. But beware of data loss, as a Instant has a resolution of nanoseconds which you will be truncating to milliseconds.

    long millis = instant.toEpochMilli() ;
    

    1487302155725


    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.

    Where to obtain the java.time classes?

    • Java SE 8 and 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 SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
      • 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.

提交回复
热议问题