Java: Date from unix timestamp

后端 未结 10 1568
北荒
北荒 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:38

    For 1280512800, multiply by 1000, since java is expecting milliseconds:

    java.util.Date time=new java.util.Date((long)timeStamp*1000);
    

    If you already had milliseconds, then just new java.util.Date((long)timeStamp);

    From the documentation:

    Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

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

    tl;dr

    Instant.ofEpochSecond( 1_280_512_800L )
    

    2010-07-30T18:00:00Z

    java.time

    The new java.time framework built into Java 8 and later is the successor to Joda-Time.

    These new classes include a handy factory method to convert a count of whole seconds from epoch. You get an Instant, a moment on the timeline in UTC with up to nanoseconds resolution.

    Instant instant = Instant.ofEpochSecond( 1_280_512_800L );
    

    instant.toString(): 2010-07-30T18:00:00Z

    See that code run live at IdeOne.com.

    Asia/Kabul or Asia/Tehran time zones ?

    You reported getting a time-of-day value of 22:30 instead of the 18:00 seen here. I suspect your PHP utility is implicitly applying a default time zone to adjust from UTC. My value here is UTC, signified by the Z (short for Zulu, means UTC). Any chance your machine OS or PHP is set to Asia/Kabul or Asia/Tehran time zones? I suppose so as you report IRST in your output which apparently means Iran time. Currently in 2017 those are the only zones operating with a summer time that is four and a half hours ahead of UTC.

    Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST or IRST as they are not true time zones, not standardized, and not even unique(!).

    If you want to see your moment through the lens of a particular region's time zone, apply a ZoneId to get a ZonedDateTime. Still the same simultaneous moment, but seen as a different wall-clock time.

    ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
    ZonedDateTime zdt = instant.atZone( z );  // Same moment, same point on timeline, but seen as different wall-clock time.
    

    2010-07-30T22:30+04:30[Asia/Tehran]

    Converting from java.time to legacy classes

    You should stick with the new java.time classes. But you can convert to old if required.

    java.util.Date date = java.util.Date.from( instant );
    

    Joda-Time

    UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

    FYI, the constructor for a Joda-Time DateTime is similar: Multiply by a thousand to produce a long (not an int!).

    DateTime dateTime = new DateTime( ( 1_280_512_800L * 1000_L ), DateTimeZone.forID( "Europe/Paris" ) );
    

    Best to avoid the notoriously troublesome java.util.Date and .Calendar classes. But if you must use a Date, you can convert from Joda-Time.

    java.util.Date date = dateTime.toDate();
    

    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.

    You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for 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 (<26), 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.

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

    For kotlin

    fun unixToDate(timeStamp: Long) : String? {
        val time = java.util.Date(timeStamp as Long * 1000)
        val sdf = SimpleDateFormat("yyyy-MM-dd")
        return sdf.format(time)
    
    }
    
    0 讨论(0)
  • 2020-11-22 04:43

    If you are converting a timestamp value on a different machine, you should also check the timezone of that machine. For example;

    The above decriptions will result different Date values, if you run with EST or UTC timezones.

    To set the timezone; aka to UTC, you can simply rewrite;

        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
        java.util.Date time= new java.util.Date((Long.parseLong(timestamp)*1000));
    
    0 讨论(0)
提交回复
热议问题