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

How to convert epoch to mySQL timestamp in JAVA

Как преобразовать epoch в метку времени MySQL в JAVA

Как получить формат метки времени MySQL в mySQLtimestamp?

long epochNow = System.currentTimeMillis()/1000;
long epochWeek = 604800;
long date7daysAgo = epochNo2013 w - epochWeek;
String mySQLtimestamp = /* 2013-09-23:50:00 */
Переведено автоматически
Ответ 1

java.time

С выпуском Java SE 8 в марте 2014 года устаревший и подверженный ошибкам устаревший API даты и времени (java.util типы даты и времени и тип их форматирования, SimpleDateFormat и т.д.) был заменен java.time современным API даты и времени *. В следующей таблице показано сопоставление типов ANSI SQL с java.time типами:































ANSI SQLJava SE 8
ДатаLocalDate
ВРЕМЯLocalTime
МЕТКА ВРЕМЕНИLocalDateTime
ВРЕМЯ С ЧАСОВЫМ ПОЯСОМOffsetTime
МЕТКА ВРЕМЕНИ С ЧАСОВЫМ ПОЯСОМOffsetDateTime

Обратите внимание, что ZonedDateTime и Instant не поддерживаются ни одним драйвером JDBC, тогда как некоторые драйверы, например PostgreSQL, также не поддерживают OffsetTime / TIME [ WITHOUT TIMEZONE ]. Также обратите внимание, что все OffsetDateTime экземпляры должны быть в UTC (иметь смещение 0). Это потому, что серверная часть хранит их как UTC.

Как использовать это в JDBC?

Ниже приведен пример кода для вставки текущего значения OffsetDateTime в UTC, в columnfoo (который имеет TIMESTAMP WITH TIMEZONE тип):

OffsetDateTime odt = Instant.now().atOffset(ZoneOffset.UTC);
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, odt);
st.executeUpdate();
st.close();

An Instant представляет мгновенную точку на временной шкале и не зависит от часового пояса, т. е. Имеет смещение часового пояса на +00:00 часы.

Ниже приведен пример кода для извлечения OffsetDateTime из columnfoo:

Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE <some condition>");
while (rs.next()) {
// Assuming the column index of columnfoo is 1
OffsetDateTime odt = rs.getObject(1, OffsetDateTime.class));
System.out.println(odt);
}
rs.close();
st.close();

На всякий случай, если вам нужно преобразовать OffsetDateTime в другой с другим смещением:

Есть несколько способов сделать это, но я в основном использую OffsetDateTime#withOffsetSameInstant, для преобразования OffsetDateTime в другой с другим смещением часового пояса, например

import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class Main {
public static void main(String[] args) {
// A sample OffsetDateTime in UTC.
OffsetDateTime odt = Instant.now().atOffset(ZoneOffset.UTC);
System.out.println(odt);

OffsetDateTime offsetTimeAtOffset0100 = odt.withOffsetSameInstant(ZoneOffset.of("+02:00"));
System.out.println(offsetTimeAtOffset0100);

// Time at JVM's default timezone offset
ZoneOffset jvmTzOffset = ZonedDateTime.now(ZoneId.systemDefault()).getOffset();
OffsetDateTime offsetTimeAtJvmTzOffset = odt.withOffsetSameInstant(jvmTzOffset);
System.out.println(offsetTimeAtJvmTzOffset);
}
}

Вывод:

2021-05-29T13:36:15.258076Z
2021-05-29T15:36:15.258076+02:00
2021-05-29T14:36:15.258076+01:00

Некоторые моменты, связанные с приведенным выше кодом:


  1. The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).

  2. The code converts odt into two instances of OffsetDateTime - each in a different way. The first instance is with a fixed timezone offset of +02:00 hours whereas the second one is with the timezone offset of the JVM. Note that the timezone offset of a place observing DST changes as per the summer/winter time. Therefore, if a place observes DST, instead of using a fixed timezone offset e.g. +02:00 hours; we should get it from the API.

  3. My JVM's timezone is Europe/London and currently its offset is +01:00 hours.

Learn more about the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Ответ 2

Why not use a normal Date all along?

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -7);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String output = formatter.format(cal.getTime());
2024-02-03 02:35 java mysql