要获取Java中的当前时间戳:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//2016-11-16 06:43:19.77
这是两个Java示例,向您展示如何获取Java中的当前时间戳。 (使用Java 8更新)
1. java.sql.Timestamp
获得当前java.sql.Timestamp
两种方法
TimeStampExample.java
package com.mkyong.date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeStampExample {
private static final SimpleDateFormat sdf = 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);
//method 2 - via Date
Date date = new Date();
System.out.println(new Timestamp(date.getTime()));
//return number of milliseconds since January 1, 1970, 00:00:00 GMT
System.out.println(timestamp.getTime());
//format timestamp
System.out.println(sdf.format(timestamp));
}
}
输出量
2016-11-16 06:43:19.77
2016-11-16 06:43:19.769
1479249799770
2016.11.16.06.43.19
2. java.time.Instant
在Java 8中,可以将java.sql.Timestamp
转换为新的java.time.Instant
InstantExample.java
package com.mkyong.date;
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);
//return number of milliseconds since January 1, 1970, 00:00:00 GMT
System.out.println(timestamp.getTime());
// Convert timestamp to instant
Instant instant = timestamp.toInstant();
System.out.println(instant);
//return number of milliseconds since the epoch of 1970-01-01T00:00:00Z
System.out.println(instant.toEpochMilli());
// Convert instant to timestamp
Timestamp tsFromInstant = Timestamp.from(instant);
System.out.println(tsFromInstant.getTime());
}
}
输出量
2016-11-16 06:55:40.11
1479250540110
2016-11-15T22:55:40.110Z
1479250540110
1479250540110
参考文献
- java.sql.Timestamp JavaDoc
- java.time.Instant JavaDoc
标签: 日期 即时 java.time 时间戳
翻译自: https://mkyong.com/java/how-to-get-current-timestamps-in-java/
今天的文章java 获取当前时间的三种方法_js获取时间戳精确到秒分享到此就结束了,感谢您的阅读。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/69936.html