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

JDK中常用的Java日期时间函数

发布时间:2023-10-20 11:55:46

在JDK中,有许多常用的Java日期时间函数可供使用。以下是其中一些常用的函数:

1. Date() - 返回当前系统日期和时间。

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

2. SimpleDateFormat() - 将日期对象格式化为指定的日期字符串,或将日期字符串解析为日期对象。

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

3. Calendar.getInstance() - 返回一个表示当前日期和时间的Calendar对象。

Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());

4. calendar.set(int year, int month, int day) - 设置Calendar对象的年、月和日。

calendar.set(2022, Calendar.MARCH, 14);
System.out.println(calendar.getTime());

5. calendar.get(int field) - 返回指定字段的值,如年、月、日、时、分、秒等。

int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(year + "-" + month + "-" + day);

6. calendar.add(int field, int amount) - 根据指定的字段和增量值,修改Calendar对象的日期和时间。

calendar.add(Calendar.DAY_OF_MONTH, 7);
System.out.println(calendar.getTime());

7. DateTimeFormatter.ofPattern(String pattern) - 返回一个自定义格式的日期时间格式化器。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.now();
String formattedDateTime = dateTime.format(formatter);
System.out.println(formattedDateTime);

8. LocalDateTime.now() - 返回当前日期和时间的LocalDateTime对象。

LocalDateTime now = LocalDateTime.now();
System.out.println(now);

9. LocalDate.now() - 返回当前日期的LocalDate对象。

LocalDate currentDate = LocalDate.now();
System.out.println(currentDate);

10. LocalTime.now() - 返回当前时间的LocalTime对象。

LocalTime currentTime = LocalTime.now();
System.out.println(currentTime);

这些是JDK中常用的Java日期时间函数,可以根据需要使用它们来操作日期和时间。