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

实用的Java日期时间函数与格式化

发布时间:2023-10-22 14:53:28

Java提供了许多实用的日期时间函数和格式化方法,用于处理日期时间的计算、转换和格式化。以下是一些常用的Java日期时间函数和格式化示例:

1. 获取当前日期和时间:

   import java.util.Date;
   
   Date now = new Date();
   System.out.println(now);  // 输出当前日期和时间
   

2. 获取指定格式的当前日期和时间:

   import java.time.LocalDateTime;
   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);  // 输出格式化后的当前日期和时间
   

3. 将字符串解析为日期对象:

   import java.time.LocalDate;
   import java.time.format.DateTimeFormatter;
   
   String dateStr = "2022-01-01";
   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
   LocalDate date = LocalDate.parse(dateStr, formatter);
   System.out.println(date);  // 输出解析后的日期对象
   

4. 获取指定日期的年、月、日:

   import java.time.LocalDate;
   
   LocalDate date = LocalDate.now();
   int year = date.getYear();
   int month = date.getMonthValue();
   int day = date.getDayOfMonth();
   System.out.println("年:" + year + " 月:" + month + " 日:" + day);
   

5. 计算日期的差值:

   import java.time.LocalDate;
   import java.time.Period;
   
   LocalDate startDate = LocalDate.of(2022, 1, 1);
   LocalDate endDate = LocalDate.of(2022, 12, 31);
   Period period = Period.between(startDate, endDate);
   int years = period.getYears();
   int months = period.getMonths();
   int days = period.getDays();
   System.out.println("年差:" + years + " 月差:" + months + " 天差:" + days);
   

6. 增加或减少日期的天数、月数或年数:

   import java.time.LocalDate;
   import java.time.Period;
   
   LocalDate date = LocalDate.now();
   LocalDate newDate = date.plusDays(7);  // 增加7天
   LocalDate sameDate = date.minusMonths(1);  // 减少1个月
   LocalDate futureDate = date.plusYears(5);  // 增加5年
   

7. 格式化日期对象为字符串:

   import java.time.LocalDate;
   import java.time.format.DateTimeFormatter;
   
   LocalDate date = LocalDate.now();
   DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
   String formattedDate = date.format(formatter);
   System.out.println(formattedDate);  // 输出格式化后的日期字符串
   

8. 获取指定月份的天数:

   import java.time.YearMonth;

   YearMonth yearMonth = YearMonth.of(2022, 2);
   int daysInMonth = yearMonth.lengthOfMonth();
   System.out.println("2月份的天数:" + daysInMonth);
   

9. 判断是否为闰年:

   import java.time.Year;
   
   int year = 2022;
   boolean isLeap = Year.of(year).isLeap();
   System.out.println(year + "年是否为闰年:" + isLeap);
   

10. 比较两个日期的先后顺序:

    import java.time.LocalDate;
    
    LocalDate date1 = LocalDate.of(2022, 1, 1);
    LocalDate date2 = LocalDate.of(2022, 12, 31);
    int compareValue = date1.compareTo(date2);
    System.out.println("date1和date2的比较结果:" + compareValue);
    

这些Java日期时间函数和格式化方法可以方便地处理日期时间的计算、转换和格式化,让开发者能更好地操作和展示日期时间相关的信息。