1. Get the current time
Calendar cal = Calendar.getInstance(); System.out.println(cal.getTime()); Date date=new Date(); System.out.println(date);
The output results are consistent:
Tue Jan 05 11:18:46 CST 2021
Tue Jan 05 11:18:46 CST 2021
2. Get the year, month, and day
Date.getDay() and other methods to get year, month and day are obsolete. Of course, if you have to use it, it is not impossible.
But currently it is recommended to use Calendar to get the year, month, and day
//year System.out.println(calendar.get(Calendar.YEAR)); //month System.out.println(calendar.get(Calendar.MONTH)); //day System.out.println(calendar.get(Calendar.DAY_OF_MONTH)); //Time System.out.println(calendar.get(Calendar.HOUR_OF_DAY)); //Minute System.out.println(calendar.get(Calendar.MINUTE)); //second System.out.println(calendar.get(Calendar.SECOND));
3. Date formatting
Date date = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
The output is as follows:
2021-01-05 11:32:44
Date date = new Date(); System.out.println(date); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // Date type is converted to yyyy-MM-dd HH:mm:ss type System.out.println(sdf.format(date));
The output is as follows:
Tue Jan 05 11:33:33 CST 2021
2021-01-05 11:33:33
4. Add xx year/month/day/hour/second to the date
Date date=new Date(); System.out.println(date); System.out.println(DateUtils.addDays(date, -7)); System.out.println(DateUtils.addMonths(date, -1)); System.out.println(DateUtils.addHours(date, -1)); System.out.println(DateUtils.addMinutes(date, -1)); System.out.println(DateUtils.addYears(date, -1));
The output is as follows:
Tue Jan 05 11:36:32 CST 2021
Tue Dec 29 11:36:32 CST 2020
Sat Dec 05 11:36:32 CST 2020
Tue Jan 05 10:36:32 CST 2021
Tue Jan 05 11:35:32 CST 2021
Sun Jan 05 11:36:32 CST 2020
Date date = new Date(); System.out.println((new SimpleDateFormat("yyyy-MM-dd")).format(date)); Calendar cal = Calendar.getInstance(); cal.setTime(date); //year cal.add(Calendar.YEAR, 3); System.out.println((new SimpleDateFormat("yyyy-MM-dd")).format(cal.getTime())); //day cal.add(Calendar.DATE, 3); System.out.println((new SimpleDateFormat("yyyy-MM-dd")).format(cal.getTime()));
The output is as follows:
2021-01-05
2024-01-05
2024-01-08