Java: Date from unix timestamp

后端 未结 10 1579
北荒
北荒 2020-11-22 04:10

I need to convert a unix timestamp to a date object.
I tried this:

java.util.Date time = new java.util.Date(timeStamp);

Timestamp value

相关标签:
10条回答
  • 2020-11-22 04:19

    java.time

    Java 8 introduced a new API for working with dates and times: the java.time package.

    With java.time you can parse your count of whole seconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. The result is an Instant.

    Instant instant = Instant.ofEpochSecond( timeStamp );
    

    If you need a java.util.Date to interoperate with old code not yet updated for java.time, convert. Call new conversion methods added to the old classes.

    Date date = Date.from( instant );
    
    0 讨论(0)
  • 2020-11-22 04:24

    Sometimes you need to work with adjustments.

    Don't use cast to long! Use nanoadjustment.

    For example, using Oanda Java API for trading you can get datetime as UNIX format.

    For example: 1592523410.590566943

        System.out.println("instant with nano = " + Instant.ofEpochSecond(1592523410, 590566943));
        System.out.println("instant = " + Instant.ofEpochSecond(1592523410));
    

    you get:

    instant with nano = 2020-06-18T23:36:50.590566943Z
    instant = 2020-06-18T23:36:50Z
    

    Also, use:

     Date date = Date.from( Instant.ofEpochSecond(1592523410, 590566943) );
    
    0 讨论(0)
  • 2020-11-22 04:33

    Date's constructor expects the timeStamp value to be in milliseconds. Multiply your timestamp's value with 1000, then pass it to the constructor.

    0 讨论(0)
  • 2020-11-22 04:33
    Date d = new Date(i * 1000 + TimeZone.getDefault().getRawOffset());
    
    0 讨论(0)
  • 2020-11-22 04:35

    Looks like Calendar is the new way to go:

    Calendar mydate = Calendar.getInstance();
    mydate.setTimeInMillis(timestamp*1000);
    out.println(mydate.get(Calendar.DAY_OF_MONTH)+"."+mydate.get(Calendar.MONTH)+"."+mydate.get(Calendar.YEAR));
    

    The last line is just an example how to use it, this one would print eg "14.06.2012".

    If you have used System.currentTimeMillis() to save the Timestamp you don't need the "*1000" part.

    If you have the timestamp in a string you need to parse it first as a long: Long.parseLong(timestamp).

    https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

    0 讨论(0)
  • 2020-11-22 04:36

    This is the right way:

    Date date = new Date ();
    date.setTime((long)unix_time*1000);
    
    0 讨论(0)
提交回复
热议问题