The most commonly used time class in java is java.util.Date. Since the methods of getting year, month, and day such as getYear() and getMonth() are abandoned in the Date class, so we need to use Calendar to obtain the more commonly used date formats such as year, month, day, and week.
Note: All the following codes have been tested and passed in jdk1.6. Other versions may use differently, please note!
How to use Date and String interchange
/** * The usage of Date and String interchange, SimpleDateFormat is required here. */Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); String dateString = formatter.format(currentTime); Date date = formatter.parse(dateString);The mutual transfer between Date and Calendar
/** * The mutual conversion between Date and Calendar*/Calendar cal = Calendar.getInstance();cal.setTime(new Date());Date date1 = cal.getTime();
Use Calendar to obtain time domains such as year, month, week, day, hour, etc.
/** * Use Calendar to obtain time domains such as year, month, week, day, and hour*/cal.get(Calendar.YEAR);cal.get(Calendar.MONTH);cal.get(Calendar.WEEK_OF_MONTH);cal.get(Calendar.DAY_OF_MONTH);cal.get(Calendar.DAY_OF_MONTH);
Add or subtract time
/** * Add and subtract the time*/cal.add(Calendar.MONTH, 1);System.out.println(cal.getTime());
Calculate what day of the week a given date belongs to
Calendarcal = Calendar.getInstance();cal.set(2016,08,01);String[] strDays = new String[] { "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" };System.out.println(strDays[cal.get(Calendar.DAY_OF_WEEK) - 1]);The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.