Java Date and Time Processing
Java Date and Time Processing
Labels: Java Basics
Date
java.util.DateThe object represents an instant accurate to milliseconds.DateIt has existed since JDK1.0 and has a long history.Powerful functions (including date and time), So most of hisConstructor/MethodAll alreadyDeprecatedTherefore, it is no longer recommended (if you use it rashly, performance/security issues may occur ); below I will introduce only a few of the remaining methods (the common points of these methods are:DateConversion from millisecond Value):
Constructor
Date(): Calls at the underlying layer
System.currentTimeMillis()As the date parameter.
Date(long date): Generate a Date object based on the specified long integer (milliseconds passed since 00:00:00.
Method
boolean after(Date when): Test whether the date this is after the specified date when;
boolean before(Date when): Test whether the date this is before the specified date when;
long getTime(): Get the millisecond value between 00:00:00 and Date;
void setTime(long time): Set the time. time indicates the same time.
/** * Created by jifang on 15/12/30. */public class DateTest { @Test public void test() { Date dateBefore = new Date(); Date dateAfter = new Date(System.currentTimeMillis() + 1); System.out.println("before: " + dateBefore.getTime()); System.out.println("after: " + dateAfter.getTime()); System.out.println(dateBefore.before(dateAfter)); System.out.println(dateAfter.after(dateBefore)); dateBefore.setTime(System.currentTimeMillis()); System.out.println(dateBefore.getTime()); System.out.println(dateBefore.before(dateAfter)); }}
Calendar
BecauseDateThere are defects, so JDK providesjava.util.CalendarTo process the date and time.CalendarIt is an abstract class and a template for all Calendar classes. Therefore, we can inherit Calendar to implement other calendars (such as the lunar Calendar );
Java provides a default Implementation of Calendar.java.util.GregorianCalendarGregali calendar (in fact, JDK also provides a Japanese calendar by default)java.util.JapaneseImperialCalendar).Calendar.getInstance();The default value is obtained.GregorianCalendar,getInstance()The method is called internally.cal = new GregorianCalendar(zone, aLocale);Generate a calendar instance.
Calendar can also be freely converted from Date.
public class CalendarTest { @Test public void test() { Calendar calendar = Calendar.getInstance(); Date date = calendar.getTime(); Calendar newCalendar = Calendar.getInstance(); newCalendar.setTime(date); System.out.println(calendar.get(Calendar.DATE)); }}
The Calendar class provides a large number of methods to access/modify date/time. the commonly used methods are as follows:
| Method |
Description |
void add(int field, int amount) |
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. |
int get(int field) |
Returns the value of the given calendar field. |
int getActualMaximum(int field) |
Returns the maximum value that the specified calendar field cocould have, given the time value of this Calendar. |
int getActualMinimum(int field) |
Returns the minimum value that the specified calendar field cocould have, given the time value of this Calendar. |
void roll(int field, int amount) |
Adds the specified (signed) amount to the specified calendar field without changing larger fields. |
void set(int field, int value) |
Sets the given calendar field to the given value. |
void set(int year, int month, int date) |
Sets the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH. |
void set(int year, int month, int date, int hourOfDay, int minute, int second) |
Sets the values for the fields YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, and SECOND. |
void setTimeInMillis(long millis) |
Sets this Calendar's current time from the given long value. |
long getTimeInMillis() |
Returns this Calendar's time value in milliseconds. |
Many of the methods above require an int-type field parameter. field is a class variable of the Calendar class, such:Calendar.DATE Calendar.MONTH Calendar.HOUR Calendar.DAY_OF_WEEKBut it must be noted thatCalendar.MONTHThe starting value of a month is not 1, but 0 (January: 0, February: 1 ...),Calendar.DAY_OF_WEEKIndicates the week. The start value is Sunday (Sunday: 1, Monday: 2 ...) (For other details, see the JDK documentation ).
Note:
If
CalendarIf no value is set, it is set based on the current system time.
add(int field, int amount)Is very powerful, if you need to add a field, let the amount is a positive number, if you want to reduce the value of a field, let the amount is negative. and when it exceeds the permitted range
Carry.
roll()Meaning and usage and
add()But when the modified field exceeds the permitted range, it will not carry.
set(int field, int value)The method has the function of delayed modification: it sets a member variable internally to indicate that the Calendar field has been modified, but the time represented by the Calendar is not modified immediately, it will wait until the next call
Get/getTime/getTimeInMillis/add/rollThe calendar time is recalculated.
public int get(int field){ complete(); return internalGet(field);}
public long getTimeInMillis() { if (!isTimeSet) { updateTime(); } return time;}
Test
Public class CalendarTest {@ Test public void test () {Calendar calendar = Calendar. getInstance (); calendar. set (2011, Calendar. JULY, 31); calendar. set (Calendar. MONTH, Calendar. SEPTEMBER); // release the following comments and then test // System. out. println (calendar. get (Calendar. MONTH) + 1 + "MONTH" + calendar. get (Calendar. DATE) + "day"); calendar. set (Calendar. DATE, 5); System. out. println (calendar. get (Calendar. MONTH) + 1 + "MONTH" + calendar. get (Calendar. DATE) + "day ");}}
Date formatting
Converts a string to a date object (format/parse)
DateFormat
java.text.DateFormatIs an abstract class. It provides the following methods to obtain the DateFormat object.
| Method |
Description |
static DateFormat getDateInstance() |
Gets the date formatter with the default formatting style for the default locale. |
static DateFormat getDateTimeInstance() |
Gets the date/time formatter with the default formatting style for the default locale. |
static DateFormat getTimeInstance() |
Gets the time formatter with the default formatting style for the default locale. |
In fact, the above three methods can also specify the date/time style, suchFULL/LONG/MEDIUM/SHOTThese four style parameters can be used to control the generated formatted string. However, it is rarely used in actual development.DateFormatClass, so we will not introduce it too much, but we usually use its subclassSimpleDateFormat(In fact, the above several getXxxInstance methods also return SimpleDateFormat instances)
DateFormat dateFormat = DateFormat.getTimeInstance();System.out.println(dateFormat.getClass().getName());
SimpleDateFormat
java.text.SimpleDateFormatYou can flexibly format the Date, or parse the Date strings in various formats.SimpleDateFormatYou need to inputPatternString, thisPatternIt is not a regular expression, but a date template string.
/** * Created by jifang on 15/12/30. */public class FormatTest { @Test public void client() throws ParseException { DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // Date -> String Date date = new Date(System.currentTimeMillis()); System.out.println(format.format(date)); // String -> Date String timeString = "2015-12-30 08:53:21"; Date newDate = format.parse(timeString); System.out.println(newDate); }}
When formatting time and date, the following methods are most commonly used:
| Method |
Description |
Summary |
String format(Date date) |
Formats a Date into a date/time string. |
Date-> String |
Date parse(String source) |
Parses text from the beginning of the given string to produce a date. |
String-> Date |
Of course,PatternWe can also customize the form based on our needs:
@ Test public void client () throws ParseException {DateFormat format = new SimpleDateFormat ("MM, dd, yy, hh, mm, ss seconds "); // Date-> String Date date = new Date (System. currentTimeMillis (); System. out. println (format. format (date); // String-> Date String timeString = "15-, January 1, December 30"; Date newDate = format. parse (timeString); System. out. println (newDate );}
We can see thatSimpleDateFormatThe format of a Date and the parsing of a string into a Date depend entirely on the pattern parameter specified when the object is created.PatternParameters andSimpleDateFormatFor more information, see the JDK documentation.
Database storage time practice
Because time storage involves cross-Time Zone issues (the sameUTC timeIn each time zone, different values are displayed. Therefore, we need to be careful when inserting time into the database. We cannot simply use the data provided by the database.TIMESTAMPOrDATETIMEType. We recommend that you use an integer (for exampleBIGINT64-bit and Java Long type) to store`1970-01-01 00:00:00ToTime PointThe number of milliseconds that have elapsed (For details, refer to: how to correctly process the time ).
The advantage of this method is that when reading time (a Long integer), you only need to format it as a string according to the user's time zone to display it correctly. of course, this also has a defect, that is, when we directly view the database by the developer/DB, we only see a string of numbers and cannot clearly know the corresponding time and date.
How to store the databaseTime ValueNext, let's talk about the database conversion problem during [deposit/read:
Converting from Date to Long is easy:
Date date = new Date();long time = date.getTime();
To convert a String from Long to a time String, we need
SimpleDateFormatMethod:
// Formats an object to produce a string.| Object -> StringString format(Object obj);
// Of course, the pattern String can be specified as another value String time = new SimpleDateFormat ("yyyy-MM-dd hh: mm: ss"). format (System. currentTimeMillis ());
Configure the singleton Formatter
Since there is only one format for time formatting and parsing in a project (we should not want to parse the formatted time until the end), so we do not need to use it every time.newOutputFormatterThis will not only cause performance degradation, but also cause errors due to inconsistent time formats. Therefore, we can loadFormatter Bean, In use@AutowiredYou can:
@Autowiredprivate DateFormat dateFormatter;...String time = dateFormatter.format(System.currentTimeMillis());