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

Java中的日期和时间函数:处理日期和时间格式的示例代码。

发布时间:2023-06-24 22:27:42

Java中提供了一系列的日期和时间函数,在处理日期和时间格式的时候非常的方便。下面是一些常用的日期和时间函数的示例代码。

1. 获取当前日期和时间

import java.time.LocalDateTime;

LocalDateTime now = LocalDateTime.now();
System.out.println("当前日期和时间:" + now);

2. 获取日期

LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
System.out.println("当前日期:" + year + "-" + month + "-" + day);

3. 获取时间

LocalDateTime now = LocalDateTime.now();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
System.out.println("当前时间:" + hour + ":" + minute + ":" + second);

4. 格式化日期和时间

import java.time.format.DateTimeFormatter;

LocalDateTime now = LocalDateTime.now();

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

System.out.println("格式化后的日期和时间:" + formattedDateTime);

5. 比较日期和时间

import java.time.LocalDate;
import java.time.LocalDateTime;

LocalDateTime now = LocalDateTime.now();
LocalDate date = LocalDate.of(2022, 1, 1);

boolean isAfter = now.isAfter(date.atStartOfDay());
boolean isBefore = now.isBefore(date.atStartOfDay());

System.out.println("当前日期和时间是否在指定日期之后:" + isAfter);
System.out.println("当前日期和时间是否在指定日期之前:" + isBefore);

6. 增加或减少时间

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

LocalDateTime now = LocalDateTime.now();
LocalDateTime later = now.plus(1, ChronoUnit.HOURS);
LocalDateTime earlier = now.minusMinutes(30);

System.out.println("当前日期和时间:" + now);
System.out.println("增加1小时后的日期和时间:" + later);
System.out.println("减少30分钟后的日期和时间:" + earlier);

7. 判断是否为闰年

import java.time.Year;

int year = 2020;
boolean isLeap = Year.isLeap(year);
System.out.println(year + "是否为闰年:" + isLeap);

8. 获取某月的天数

import java.time.YearMonth;

int year = 2022;
int month = 2;
YearMonth yearMonth = YearMonth.of(year, month);

int daysInMonth = yearMonth.lengthOfMonth();
System.out.println(year + "年" + month + "月的天数:" + daysInMonth);

9. 获取两个日期的相差天数

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

LocalDate startDate = LocalDate.of(2022, 1, 1);
LocalDate endDate = LocalDate.of(2022, 1, 10);

long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("2022年1月1日和2022年1月10日相差天数:" + daysBetween);

以上是Java中常用的日期和时间函数的示例代码,可以根据需要进行调用和修改。在实际开发中,合理地使用这些函数可以提高代码的效率和可维护性。