Java Date-time processing

Source: Internet
Author: User
Tags dateformat time zones locale string format time and date


Java Date-time processing





Date


java.util.DateThe object represents an instant that is accurate to milliseconds; But sinceDateJDK1.0 began to exist, has a long history and is powerful (both date and time), most of his constructors / methods have been Deprecated, Therefore, it is no longer recommended (if used rashly, there may be performance/security problems); I'll just cover a few of the few methods that are left (the common denominator of these methods is the Dateconversion to millisecond values ):


    • Constructors

      • Date(): CalledSystem.currentTimeMillis()as a date parameter at the bottom.
      • Date(long date): A Date object is generated based on the specified long integer (the number of milliseconds since 1970-1-1 00:00:00).
    • Method

      • boolean after(Date when): Tests whether this date is after the specified date;
      • boolean before(Date when): Tests whether this date is before the specified date;
      • long getTime(): Gets the millisecond value from 1979-01-01 00:00:00 to date object;
      • void setTime(long time): Sets the time, meaning the same.
 
 
/**
 * 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


BecauseDateof a flaw, the JDK also provides thejava.util.Calendarprocessing date and time.Calendaris an abstract class, is a template for all calendar classes, so we can inherit the calendar to implement other calendars (such as lunar calendar);



Java provides a default implementation of the Gregorianjava.util.GregorianCalendarGregorian calendar (in fact, the JDK also provides a Japanese calendar by defaultjava.util.JapaneseImperialCalendar), which is what we call the Calendar.Calendar.getInstance();by default, the inside of theGregorianCalendargetInstance()method callscal = new GregorianCalendar(zone, aLocale);the To generate a Gregorian calendar instance.


    • Calendar can also be converted freely with 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 number of methods for accessing/modifying date/time, commonly used in the following ways:
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 could has, given the time value of this calendar.
int getActualMinimum(int field) Returns the minimum value that the specified calendar field could has, 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 above methods require a field parameter of type int, field is a class variable of the calendar class, such as:Calendar.DATECalendar.MONTHCalendar.HOURCalendar.DAY_OF_WEEK, but it should be noted that theCalendar.MONTHstarting value of the month is not 1, but 0 (January: 0, February: 1 ...),represents the week, the starting value is Sunday (Sunday: 1, Monday: 2 ...) (Please refer to the JDK documentation for additional details).



Attention:


    • IfCalendarno related value is set, it is set at the current system time.
    • add(int field, int amount)is very powerful, if you need to add a field, let amount be positive, if you want to reduce the value of a field, let amount be negative. And when it is beyond his allowable range, a carry occurs.
    • roll()The meaning isadd()similar to the usage, but when the modified field exceeds the allowable range, he does not carry it.
    • set(int field, int value)Method has the ability to defer modification: He has set a member variable internally to indicate that the Calendar field has been modified, but the time represented by the calendars will not be immediately modified, until the next call to get/gettime/gettimeinmillis/ the calendar time will not be recalculated until add/roll.

 
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 bet and 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

Complete conversion of string and date objects (Format/parse)

DateFormat


java.text.DateFormatis an abstract class, he provides several methods to get 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 of the style, such asFULL/LONG/MEDIUM/SHOT, through the four style parameters can control the resulting format string. But because of the fact that we seldom use classes directly in our actual developmentDateFormat, we do not introduce too much to them. And what we use more often is its subclassesSimpleDateFormat( In fact, the above several Getxxxinstance method returned is also SimpleDateFormat instance)





DateFormat dateFormat = DateFormat.getTimeInstance();
System.out.println(dateFormat.getClass().getName());
SimpleDateFormat


java.text.SimpleDateFormatYou can format date in a very flexible way, or you can use it to parse dates strings in various formats.SimpleDateFormatWhen you create an object , you need to pass in a pattern string, which 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);
    }
}


There are several methods that are most commonly used when formatting time and date:


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, pattern We can also have other customized forms according to our needs:



@Test
     public void client () throws ParseException {

         DateFormat format = new SimpleDateFormat ("yy year MM month dd day hh hour mm minute ss second");

         // Date-> String
         Date date = new Date (System.currentTimeMillis ());
         System.out.println (format.format (date));

         // String-> Date
         String timeString = "December 30, 15: 00:29:29";
         Date newDate = format.parse (timeString);
         System.out.println (newDate);
     } 


You can seeSimpleDateFormathow the date is formatted into a string and how the string can be parsed into date, depending on the pattern parameter specified when the object was created, and the other pattern parameters as well asSimpleDateFormatthe method referenced in the JDK document.


Database storage Time Combat


Because time storage involves issues across time zones (the same UTC time displays different values in each time zone). Therefore, when we insert time into the database, we need to be careful not to simply use the databaseTIMESTAMPor the type providedDATETIME, It is recommended that you choose an integer type (such as theBIGINT64-bit same as the Java long type) to store`1970-01-01 00:00:00the number of milliseconds from the point in time (see: How to handle time correctly).


    • The advantage of this is that when reading the time (a long integer), you simply need to format the user's time zone as a string to correctly display it.
    • Of course, there is a flaw in this, that is, when our developers/db directly to the database, they see only a bunch of numbers, and do not know their corresponding time and date clearly.


Let's talk about how the database will store the time value , and then we'll chat about the time [deposit/read] Database conversion issues:


    • Converting from date to Long is simple:

DatedatenewDate();longdate.getTime();
    • The string we need to convert from long to a time isSimpleDateFormata method:

tostringStringString format(Object obj);

// Of course, the pattern string can be specified as other values
String time = new SimpleDateFormat ("yyyy-MM-dd hh: mm: ss"). Format (System.currentTimeMillis ()); 
Configuring a singleton Formatter


Since there is usually only one format for time formatting and parsing in a project (we should not want it to be parsed at the end of the day after formatting), we do not need to have one every time we use it.newFormatterThis will not only result in performance degradation, but may also result in a time-form of disunity and error. Therefore, we can load a Formatter Beanin the Sring container, when it is used@Autowired:



<!-Configure time formatter->
<bean id = "dateFormatter" class = "java.text.SimpleDateFormat">
     <constructor-arg value = "yyyy-MM-dd HH: mm: ss" />
</ bean>
@Autowired
private DateFormat dateFormatter;

...

String time = dateFormatter.format (System.currentTimeMillis ());

Java Date-time processing


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.