首页 课程 师资 教程 报名

Java当前时间戳的获取方法

  • 2022-08-30 10:37:47
  • 2072次 动力节点

本文展示了几个 Java 示例来获取 Java 中的当前日期时间或时间戳。(使用 Java 8 更新)。

代码片段

  // 2021-03-24 16:48:05.591
  Timestamp timestamp = new Timestamp(System.currentTimeMillis());
  // 2021-03-24 16:48:05.591
  Date date = new Date();
  Timestamp timestamp2 = new Timestamp(date.getTime());
  // convert Instant to Timestamp
  Timestamp ts = Timestamp.from(Instant.now())
  // convert ZonedDateTime to Instant to Timestamp
  Timestamp ts = Timestamp.from(ZonedDateTime.now().toInstant()));
  // convert Timestamp to Instant
  Instant instant = ts.toInstant();

1. Java时间戳示例

以下程序用于java.sql.Timestamp获取当前时间戳并使用SimpleDateFormat.

package com.mkyong.app;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeStampExample {
    // 2021.03.24.16.34.26
    private static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
    // 2021-03-24T16:44:39.083+08:00
    private static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    // 2021-03-24 16:48:05
    private static final SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static void main(String[] args) {
        // method 1
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        System.out.println(timestamp);                      // 2021-03-24 16:34:26.666
        // method 2 - via Date
        Date date = new Date();
        System.out.println(new Timestamp(date.getTime()));  // 2021-03-24 16:34:26.666                                                            // number of milliseconds since January 1, 1970, 00:00:00 GMT
        System.out.println(timestamp.getTime());            // 1616574866666
        System.out.println(sdf1.format(timestamp));         // 2021.03.24.16.34.26
        System.out.println(sdf2.format(timestamp));         // 2021-03-24T16:48:05.591+08:00
        System.out.println(sdf3.format(timestamp));         // 2021-03-24 16:48:05
    }
}

输出

2021-03-24 16:48:05.591
2021-03-24 16:48:05.591
1616575685591
2021.03.24.16.48.05
2021-03-24T16:48:05.591+08:00
2021-03-24 16:48:05

2. 将 Instant 转换为时间戳

这个例子展示了如何在新的 Java 8java.time.Instant和旧的java.sql.Timestamp.

  // convert Instant to Timestamp
  Timestamp ts = Timestamp.from(Instant.now())
  // convert Timestamp to Instant
  Instant instant = ts.toInstant();
package com.mkyong.app;
import java.sql.Timestamp;
import java.time.Instant;
public class InstantExample {
  public static void main(String[] args) {
      Timestamp timestamp = new Timestamp(System.currentTimeMillis());
      System.out.println(timestamp);                  // 2021-03-24 17:12:03.311
      System.out.println(timestamp.getTime());        // 1616577123311
      // Convert Timestamp to Instant
      Instant instant = timestamp.toInstant();
      System.out.println(instant);                    // 2021-03-24T09:12:03.311Z
      System.out.println(instant.toEpochMilli());     // 1616577123311
      // Convert Instant to Timestamp
      Timestamp tsFromInstant = Timestamp.from(instant);
      System.out.println(tsFromInstant.getTime());    // 1616577123311
  }
}

输出

2021-03-24 17:12:03.311
1616577123311
2021-03-24T09:12:03.311Z
1616577123311
1616577123311

3. 将时间戳插入表中

在java.sql.TimestampJDBC 编程中仍然被广泛使用。请参阅以下转换:

  // Java 8, java.time.*
  // convert LocalDateTime to Timestamp
  preparedStatement.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now()));
  // convert Instant to Timestamp
  preparedStatement.setTimestamp(1, Timestamp.from(Instant.now()));
  // Convert ZonedDateTime to Instant to Timestamp
  preparedStatement.setTimestamp(3, Timestamp.from(ZonedDateTime.now().toInstant()));

下面的示例是将 aTimestamp插入表的 JDBC 示例。

package com.mkyong.app;
import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDateTime;
public class JdbcExample {
  private static final String SQL_INSERT = "INSERT INTO EMPLOYEE (NAME, SALARY, CREATED_DATE) VALUES (?,?,?)";
  public static void main(String[] args) {
      try (Connection conn = DriverManager.getConnection(
              "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
           PreparedStatement preparedStatement = conn.prepareStatement(SQL_INSERT)) {
          preparedStatement.setString(1, "mkyong");
          preparedStatement.setBigDecimal(2, new BigDecimal("799.88"));
          preparedStatement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
          // preparedStatement.setTimestamp(3, Timestamp.from(ZonedDateTime.now().toInstant()));
          // preparedStatement.setTimestamp(3, Timestamp.from(Instant.now()));
          int row = preparedStatement.executeUpdate();
          // rows affected
          System.out.println(row); //1
      } catch (SQLException e) {
          System.err.format("SQL State: %s
%s", e.getSQLState(), e.getMessage());
      } catch (Exception e) {
          e.printStackTrace();
      }
  }
}

 

选你想看

你适合学Java吗?4大专业测评方法

代码逻辑 吸收能力 技术学习能力 综合素质

先测评确定适合在学习

在线申请免费测试名额
价值1998元实验班免费学
姓名
手机
提交