实现Java中时间处理的10个函数
发布时间:2023-07-02 19:21:54
1. 获取当前时间戳:可以使用System类的currentTimeMillis()方法来获取当前时间的毫秒数。
long currentTime = System.currentTimeMillis();
2. 获取当前日期:可以使用java.util包中的Date类来获取当前的日期。
Date currentDate = new Date();
3. 格式化日期:可以使用java.text包中的SimpleDateFormat类来格式化日期。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(currentDate);
4. 解析日期字符串:可以使用SimpleDateFormat类的parse()方法来解析日期字符串。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = sdf.parse("2021-01-01");
5. 增加或减少天数:可以使用java.util.Calendar类来增加或减少指定的天数。
Calendar cal = Calendar.getInstance(); cal.setTime(currentDate); cal.add(Calendar.DAY_OF_MONTH, 1); // 增加一天 Date newDate = cal.getTime();
6. 比较两个日期:可以使用Date类的compareTo()方法来比较两个日期的先后顺序。
int result = currentDate.compareTo(anotherDate);
if (result < 0) {
// currentDate 在 anotherDate之前
} else if (result > 0) {
// currentDate 在 anotherDate之后
} else {
// currentDate 和 anotherDate相等
}
7. 计算日期差:可以使用java.time包中的LocalDate类来计算两个日期之间的天数差。
LocalDate date1 = LocalDate.of(2021, 1, 1); LocalDate date2 = LocalDate.of(2022, 1, 1); long daysDiff = ChronoUnit.DAYS.between(date1, date2);
8. 格式化时间:可以使用java.time.format包中的DateTimeFormatter类来格式化时间。
LocalDateTime currentTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedTime = currentTime.format(formatter);
9. 解析时间字符串:可以使用DateTimeFormatter类的parse()方法来解析时间字符串。
String timeString = "2021-01-01 12:00:00"; LocalDateTime parsedTime = LocalDateTime.parse(timeString, formatter);
10. 获取指定时区的当前时间:可以使用java.time包中的ZonedDateTime类来获取指定时区的当前时间。
ZoneId zone = ZoneId.of("Asia/Shanghai");
ZonedDateTime currentDateTime = ZonedDateTime.now(zone);
以上是Java中时间处理的10个常用函数,可以根据具体需求选择合适的方法来处理时间。
