This article shares common methods of Calendar time operation, the specific content is as follows
package test;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;/** * Common methods of Date and Calendar, many Date methods have been deprecated, so Calendar is the main one* * @author tuzongxun123 * */public class DateAndCalendarTest {public static void main(String[] args) {// Directly use Date to get the current system time, result: Tue May 03 08:25:44 CST 2016Date date = new Date();// Many methods in Date, such as obtaining a certain year, month, day, etc., and setting a certain year, month, day, etc., are no longer recommended. // It is recommended to use various methods of calendar instead, so no records are made // Get the milliseconds of the specified date, which is often used to compare the sizes of two dates. date.getTime();// Use Calendar to get the current system time. You need to get the Calendar object and convert it into Date output Calendar calendar = Calendar.getInstance();// This method is equivalent to getTime in Date, and get the milliseconds of the current time calendar.getTimeInMillis();// Get the date of the first day of the week where the specified date is. The default first day of the week is Sunday calendar.getFirstDayOfWeek();// Returns the year where the current calendar date is, such as 2016calendar.get(1);// Calendar is converted to Date, output result: Tue May 03 09:31:59 CST 2016Date date2 = calendar.getTime();System.out.println(date2);// Calendar sets year, month, and day, output result: Mon Jun 03 09:31:59 CST 2013// Related commonly used overloaded methods: calendar.set(year, month, date, hourOfDay, minute);// Calendar.set(year, month, date, hourOfDay, minute, second); All parameters are intcalendar.set(2013, 5, 3); System.out.println(calendar.getTime());// Use Calendar to set year, output result: Fri Jun 03 09:42:43 CST 2011calendar.set(Calendar.YEAR, 2011);System.out.println(calendar.getTime());// Set the month with Calendar and numbers, note that the month starts at 0, representing January, output result: Mon Jan 03 09:45:32 CST 2011calendar.set(Calendar.MONTH, 0);System.out.println(calendar.getTime());// Set the month with Calendar and its own constants, note that the month starts at 0, representing January, output result: Thu Feb 03 09:47:07 CST 2011calendar.set(Calendar.MONTH, Calendar.FEBRUARY);System.out.println(calendar.getTime());// Set the day with Calendar and numbers, output result: Sat Feb 05 09:48:25 CST 2011// calendar.set(Calendar.DAY_OF_MONTH, 5) The result is the same;calendar.set(Calendar.DATE, 5);System.out.println(calendar.getTime());// Set the hour calendar.set(Calendar.HOUR, 15);System.out.println(calendar.getTime());// Set Calendar time according to the number of milliseconds Calendar.setTimeInMillis(0);// Date to String, output result: 2016-05-03 09:25:29String forDate = dateToString(new Date());System.out.println(forDate);// String to Date, output result: Thu Nov 12 13:23:11 CST 2015Date strDate = stringToDate("2015-11-12 13:23:11");System.out.println(strDate);// Date to Calendar, output result: 2015Calendar calendar2 = dateToCalendar(strDate);System.out.println(calendar2.get(1));}/*** Convert the specified date type time to a string in the specified format * * @author: tuzongxun* @Title: dateToString* @param @param date* @return void* @date May 3, 2016 9:09:25 AM* @throws*/static String dateToString(Date date) {String str = "yyyy-MM-dd hh:mm:ss";SimpleDateFormat format = new SimpleDateFormat(str);String dateFormat = format.format(date);return dateFormat;}/*** Convert the string in the specified date format to the Date type* * @author: tuzongxun* @Title: StringToDate* @param @param string* @return void* @date May 3, 2016 9:16:38 AM* @throws*/static Date stringToDate(String string) {String str = "yyyy-MM-dd hh:mm:ss";SimpleDateFormat format = new SimpleDateFormat(str);Date date = new Date();try {date = format.parse(string);} catch (Exception e) {e.getStackTrace();}return date;}/*** Convert the specified date type date to Calendar type* * @author: tuzongxun* @Title: dateToCalendar* @param @param date* @return void* @date May 3, 2016 9:13:49 AM* @throws*/static Calendar dateToCalendar(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);return calendar;}}What other pitfalls are there?
Where is the pit:
In a project I came across before, I involved a function: move some data to another collection of mongodb databases every day, that is, the tables of the relational database. This collection name is a fixed name plus the year and month on which the current two months ago date is located.
This function existed before I came into contact with this project, which is a function implemented by my previous colleagues, and wrote a Java timing task.
That colleague is no longer in our company, but recently he found that this function has some problems. The data movement is not as expected. The data that should have existed in February appeared in the January table.
The root of the pit:
The mongodb-related problems are temporarily maintained by me, and this problem naturally needs to be solved by me, so I took out his code and read it. As a result, the problem was found to be the relevant methods of calendar.
To transfer data from two months ago, you must first get the date from two months ago. The relevant code for generating the table name is as follows:
private String getDataCollectionName() { Calendar calendar = Calendar.getInstance(); try { calendar.set(Calendar.DATE, -day); return "alarm_" + ToolUtils.dateToFormatStrDate(calendar.getTime(), "yyyy_MM"); } catch (Exception e) { logger.error("{}: data transforming failed,{}", this.getClass().getName(), e.getMessage()); } return null; }The problem lies in the set method of calendar, including the start and end time of the query data use later, and the same is used is calendar.set(Calendar.DATE, -day);
At first glance, this method seems to set the date to the current date minus the specified number of days, but in fact the result is not as expected as you would get the date two months ago (the day here defines 60, that is, two months).
Fill in the pit:
After finding the reason, I replaced this method and changed set to add. As for the parameters inside, it was not moved. The result proved that this method can truly realize the current function, and the result obtained is exactly the expected result.
Of course, you can also change the parameters slightly without changing the method, such as calendar.set(Calendar.DATE, calendar.get(calendar.DATE)-day);
The above is all about this article, and I hope it will be helpful for everyone to master the common methods of Calendar time operation.