2000字代码教你怎么用Java获取当前的时间戳

Java中获取当前时间戳的多种方式
本教程介绍了在Java中获取当前时间戳的多种方式,包含JDK 8及更早版本的示例。给出了一种基础示例,还列举了其他六种不同的实现方式,每种方式都有对应的代码示例。

 

在本教程中,我们将学习如何以各种方式在 java 中获取当前时间戳。 让我们跳入JDK 8 和更早版本 jdk的正确示例。

import java.sql.Timestamp; public class CurrentTimestampExample1 { public static void main(String[] args) { long timestampInMillies = System.currentTimeMillis(); Timestamp timestamp = new Timestamp(timestampInMillies); System.out.println("timestamp now : "+timestamp); } }

其他六种方式:

第一种:

import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class CurrentTimestampExample7 { public static void main(String[] args) { LocalDateTime localDateTime = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS"); String timestamp = formatter.format(localDateTime); System.out.println("timestamp now : " + timestamp); } }

第二种:

import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class CurrentTimestampExample6 { public static void main(String[] args) { ZoneId zoneId = ZoneId.systemDefault(); ZonedDateTime localDateTime = ZonedDateTime.now(zoneId); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS"); String timestamp = formatter.format(localDateTime); System.out.println("timestamp now : " + timestamp); } }

第三种:

import java.time.Instant; public class CurrentTimestampExample5 { public static void main(String[] args) { Instant instant = Instant.now(); System.out.println("timestamp now : " + instant); } }

第四种:

import java.sql.Timestamp; import java.time.Instant; public class CurrentTimestampExample4 { public static void main(String[] args) { long timeInMillis = System.currentTimeMillis(); Timestamp timestamp = new Timestamp(timeInMillis); Instant instant = timestamp.toInstant(); System.out.println("timestamp now : " + instant); } }

第五种:

import java.text.SimpleDateFormat; import java.util.Date; public class CurrentTimestampExample2 { public static void main(String[] args) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date dateNow = new Date(); String timestampNow = simpleDateFormat.format(dateNow); System.out.println("timestamp now : " + timestampNow); } }

第六种:

import java.time.Instant; import java.util.Date; public class CurrentTimestampExample2 { public static void main(String[] args) { Date dateNow = new Date(); Instant instant = dateNow.toInstant(); System.out.println("timestamp now : " + instant); } }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值