欢迎访问宙启技术站
智能推送

Java中如何使用Date函数获取系统当前时间?

发布时间:2023-09-23 17:32:48

在Java中获取系统当前时间可以使用java.util.Date类。Date类用于表示一个特定的时间点,可以通过new Date()创建当前时间的Date对象。

以下是一些常用的获取系统当前时间的方法:

1. 使用new Date()创建当前时间的Date对象。

Date currentDate = new Date();
System.out.println(currentDate);

这段代码会打印当前时间的字符串表示,例如:Wed Apr 14 09:07:33 CST 2021

2. 使用getTime()方法获取当前时间的时间戳。时间戳指的是自1970年1月1日以来经过的毫秒数。

long currentTimeMillis = currentDate.getTime();
System.out.println(currentTimeMillis);

这段代码会打印当前时间的时间戳,例如:1618390153396

3. 使用SimpleDateFormat类将Date对象格式化成特定的时间字符串。可以通过创建SimpleDateFormat对象以及指定时间格式的模式来实现。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(currentDate);
System.out.println(formattedDate);

这段代码会打印当前时间的格式化字符串,例如:2021-04-14 09:07:33

4. 使用Calendar类获取当前时间的年份、月份、日期等信息。可以通过Calendar.getInstance()方法获取当前Calendar对象,然后通过该对象的各种方法获取时间信息。

Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 月份从0开始,所以需要加1
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
System.out.println(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);

这段代码会打印当前时间的年份、月份、日期、小时、分钟和秒数,例如:2021-4-14 9:7:33

以上是一些常见的获取系统当前时间的方法,可以根据实际需求选择适合的方法来获取系统时间。