且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

java 获取当前年份、月份、日期,当月第一天和最后一天

更新时间:2022-03-25 06:55:20

  1. public class CalendarTest {  
  2.     public static void main(String[] args) {  
  3.         // 获取当前年份、月份、日期  
  4.         Calendar cale = null;  
  5.         cale = Calendar.getInstance();  
  6.         int year = cale.get(Calendar.YEAR);  
  7.         int month = cale.get(Calendar.MONTH) + 1;  
  8.         int day = cale.get(Calendar.DATE);  
  9.         int hour = cale.get(Calendar.HOUR_OF_DAY);  
  10.         int minute = cale.get(Calendar.MINUTE);  
  11.         int second = cale.get(Calendar.SECOND);  
  12.         int dow = cale.get(Calendar.DAY_OF_WEEK);  
  13.         int dom = cale.get(Calendar.DAY_OF_MONTH);  
  14.         int doy = cale.get(Calendar.DAY_OF_YEAR);  
  15.   
  16.         System.out.println("Current Date: " + cale.getTime());  
  17.         System.out.println("Year: " + year);  
  18.         System.out.println("Month: " + month);  
  19.         System.out.println("Day: " + day);  
  20.         System.out.println("Hour: " + hour);  
  21.         System.out.println("Minute: " + minute);  
  22.         System.out.println("Second: " + second);  
  23.         System.out.println("Day of Week: " + dow);  
  24.         System.out.println("Day of Month: " + dom);  
  25.         System.out.println("Day of Year: " + doy);  
  26.   
  27.         // 获取当月第一天和最后一天  
  28.         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
  29.         String firstday, lastday;  
  30.         // 获取前月的第一天  
  31.         cale = Calendar.getInstance();  
  32.         cale.add(Calendar.MONTH, 0);  
  33.         cale.set(Calendar.DAY_OF_MONTH, 1);  
  34.         firstday = format.format(cale.getTime());  
  35.         // 获取前月的最后一天  
  36.         cale = Calendar.getInstance();  
  37.         cale.add(Calendar.MONTH, 1);  
  38.         cale.set(Calendar.DAY_OF_MONTH, 0);  
  39.         lastday = format.format(cale.getTime());  
  40.         System.out.println("本月第一天和最后一天分别是 : " + firstday + " and " + lastday);  
  41.   
  42.         // 获取当前日期字符串  
  43.         Date d = new Date();  
  44.         System.out.println("当前日期字符串1:" + format.format(d));  
  45.         System.out.println("当前日期字符串2:" + year + "/" + month + "/" + day + " "  
  46.                 + hour + ":" + minute + ":" + second);  
  47.     }  
  48.