267

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 is: 1280512800

The Date should be "2010/07/30 - 22:30:00" (as I get it by PHP) but instead I get Thu Jan 15 23:11:56 IRST 1970.

How should it be done?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Ariyan
  • 14,760
  • 31
  • 112
  • 175
  • 3
    If you use Java 8 or newer: Have a look at this answer: http://stackoverflow.com/a/24703644/1115554 – micha Jul 11 '14 at 17:50
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html) are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 30 '17 at 03:02

11 Answers11

474

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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Pablo Santa Cruz
  • 176,835
  • 32
  • 241
  • 292
  • 47
    The cast to `(long)` is very important: without it the integer overflows. – mneri Jun 11 '14 at 17:18
  • is there a difference between Java.util.Date and Date? – Tomas K Aug 06 '15 at 10:49
  • 2
    @TomasK `java.util.Date` is the fully qualified name of the class. `Date` is probably the **exact same thing** provided you import the `java.util` package on your class. – Pablo Santa Cruz Aug 06 '15 at 14:03
  • @PabloSantaCruz Thank you :) – Tomas K Aug 06 '15 at 17:20
  • 5
    The cast to long is not needed. time=new java.util.Date(timeStamp*1000L) works just as well (since 1000L is a long, timestamp will be upcast to a long before the multiplication) – Tony BenBrahim Aug 24 '15 at 23:00
  • 2
    I personally would do: `Date time = new Date(TimeUnit.MILLISECONDS.convert(unixTimestamp, TimeUnit.SECONDS));` – Ryan Amaral Mar 29 '17 at 16:18
  • 4
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html) are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 30 '17 at 03:03
80

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 );
user136036
  • 11,228
  • 6
  • 46
  • 46
micha
  • 47,774
  • 16
  • 73
  • 80
  • 4
    While this Answer is correct technically, note that the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes supplant the troublesome old date-time classes such as `java.util.Date`. The old classes are legacy and should be avoided. While you can indeed convert to/from the legacy and java.time classes, it is best to stick with java.time whenever possible. – Basil Bourque Feb 07 '17 at 23:32
45

This is the right way:

Date date = new Date ();
date.setTime((long)unix_time*1000);
Marco Fantasia
  • 720
  • 8
  • 12
36

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.

Table of date-time types in Java, both modern and legacy

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?

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
26

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

Ricbit
  • 809
  • 8
  • 15
Stefan
  • 261
  • 3
  • 2
  • 8
    Warning: if `timestamp` is an integer you need to cast it to `(long)` first, otherwise you'll end up with wrong dates. `mydate.setTimeInMillis((long) timestamp*1000);` – svenkapudija Oct 01 '12 at 00:55
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Apr 02 '18 at 00:27
15

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

f1sh
  • 11,489
  • 3
  • 25
  • 51
7

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));
tmr
  • 125
  • 2
  • 9
  • 7
    I would not recomment this because this sets the timezone for the entire jvm and not just the parsing process! –  Mar 06 '14 at 17:55
3

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)

}
Arda Kazancı
  • 8,341
  • 4
  • 28
  • 50
0

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

LocalDateTime is another choice, like:

LocalDateTime.ofInstant(Instant.ofEpochSecond(unixtime), ZoneId.systemDefault())
Frank.Chang
  • 883
  • 1
  • 10
  • 10
-4
Date d = new Date(i * 1000 + TimeZone.getDefault().getRawOffset());
Masatsugu Hosoi
  • 420
  • 6
  • 7