Вопрос-ответ

Java: Date from unix timestamp

Java: дата из временной метки unix

Мне нужно преобразовать временную метку unix в объект date.
Я пробовал это:

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

Значение временной метки равно: 1280512800

Дата должна быть "2010/07/30 - 22:30:00" ( как я получаю ее с помощью PHP), но вместо этого я получаю Thu Jan 15 23:11:56 IRST 1970.

Как это должно быть сделано?

Переведено автоматически
Ответ 1

Для 1280512800 умножьте на 1000, поскольку java ожидает миллисекунды:

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

Если у вас уже были миллисекунды, то просто new java.util.Date((long)timeStamp);

Из документации:


Выделяет объект Date и инициализирует его для представления указанного количества миллисекунд, прошедших со стандартного базового времени, известного как "эпоха", а именно 1 января 1970 года, 00:00:00 GMT.


Ответ 2

java.time

В Java 8 представлен новый API для работы с датами и временем: пакет java.time.

С помощью java.time вы можете проанализировать количество целых секунд, прошедших с момента отсчета эпохи в первый момент 1970 года по UTC, 1970-01-01T00:00Z. Результатом является Instant.

Instant instant = Instant.ofEpochSecond( timeStamp );

Если вам нужно java.util.Date взаимодействовать со старым кодом, который еще не обновлен для java.time, конвертируйте. Вызовите новые методы преобразования, добавленные к старым классам.

Date date = Date.from( instant );
Ответ 3

Это правильный способ:

Date date = new Date ();
date.setTime((long)unix_time*1000);
Ответ 4

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.

java