Java datetime use method Rollup _java

Source: Internet
Author: User
Tags date1 dateformat deprecated locale

Overview of dates in Java
Date in Java is a very complex content, for a date in different language country environment, date internationalization, date and time conversion, date of addition and subtraction operation, date display format is very complex problem.

In Java, the date of operation involves several classes:
1, java.util.Date
Class Date represents a specific moment, accurate to milliseconds. Starting with JDK 1.1, you should use the Calendar class to implement conversion between date and Time fields, and use the DateFormat class to format and parse date strings. The method in date that interprets dates as year, month, day, hour, minute, and second values is deprecated.
2, Java.text.DateFormat (abstract class)
DateFormat is an abstract class of date/time format subclasses that format and parse dates or times in a language-independent way. Date/time formatting subclasses (such as SimpleDateFormat) allow formatting (that is, date-> text), parsing (text-> date), and standardization. Represents a date as a day object, or as a number of milliseconds from GMT (Greenwich Mean Time) 1970, January 1 00:00:00 this moment.
3, Java.text.SimpleDateFormat (direct subclass of DateFormat)
SimpleDateFormat is a specific class that formats and analyzes dates in a way that is relevant to the language environment. It allows for formatting (date-> text), parsing (text-> date), and normalization.
SimpleDateFormat allows you to select a pattern for any user-defined date-time format. However, it is still recommended that you create a new date-time formatter through the gettimeinstance, getdateinstance, or getdatetimeinstance in DateFormat.
4, Java.util.Calendar (abstract class)
The Calendar class is an abstract class that provides methods for a specific moment to transform between a set of calendar fields such as year, MONTH, Day_of_month, HOUR, and for manipulating calendar fields, such as getting the date of next week. Instantly available in milliseconds, it is an offset from the 00:00:00.000 (i.e. Greenwich Mean time, January 1, 1970, Gregorian calendar).
Like other locale-sensitive classes, Calendar provides a class method getinstance to get a generic object of this type. The getinstance method of the calendar returns a Calendar object that has been initialized by the current date and time.
5, Java.util.GregorianCalendar (direct subclass of Calendar)
GregorianCalendar is a specific subclass of calendar that provides a standard calendar system used by most countries in the world.
GregorianCalendar is a hybrid calendar that supports both the Julian calendar and the Gregorian calendar system with the support of a single discontinuity, which, by default, corresponds to the Gregorian calendar when the Gregorian calendars were created (some countries were created on October 15, 1582 and later in other countries). The start date can be changed by the caller by calling Setgregorianchange ().

second, the use of Java.util.Date
1, java.util.Date API Introduction
Class Java.util.Date represents a specific moment, accurate to milliseconds. Many methods are available, but many are obsolete and deprecated, and the following lists only the methods that are not obsolete:
Construction Method Summary
-------------
Date ()
Assigns a Date object and initializes the object with the current time to indicate when it was allocated (in milliseconds).
Date (long date)
Assigns a Date object and initializes the object to represent the specified number of milliseconds since the standard base time (called "Calendar (Epoch)", which is January 1, 1970 00:00:00 GMT).

Method Summary
-------------
Boolean after (Date)
Test whether this date is after the specified date.

Boolean before (Date when)
Test whether this date is before the specified date.

Object Clone ()
Returns a copy of this object.

int CompareTo (Date anotherdate)
Compare the order of two dates.

Boolean equals (Object obj)
Compares the equality of two dates.

Long GetTime ()
Returns the number of milliseconds this Date object represents since January 1, 1970 00:00:00 GMT.

int Hashcode ()
Returns the hash code value for this object.

void SetTime (long time)
Sets this Date object to represent the point in time milliseconds after 00:00:00 GMT, January 1, 1970.

String toString ()
Convert this Date object to the following form of String:dow mon dd hh:mm:ss zzz yyyy where:
Dow is one day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
Mon is the month (Feb, Mar, APR, May, June, April, Aug, Sep, Oct, Nov, Dec).
DD is a day in January (01 to 31) and is displayed as a two-bit decimal number.
HH is the hour of the day (00 to 23), displayed as a two-bit decimal number.
MM is the minute of the hour (00 to 59) and is displayed as a two-bit decimal number.
The SS is the number of seconds in minutes (00 to 61) and is displayed as a two-bit decimal number.
ZZZ is the time zone (and can reflect daylight savings). The standard time zone abbreviation includes the time zone abbreviation recognized by method parse. If you do not provide time zone information, zzz is empty, that is, no characters are included at all.
YYYY is the year, displayed as a 4-bit decimal number.

The following is a comprehensive example of a date class:

 public class TestDate {public static void main (string[] args) {TestDate testdate =
  New TestDate ();
  Testdate.getsystemcurrenttime ();
 Testdate.getcurrentdate (); 
 /** * Gets the system current time * System.currenttimemillis () returns the system current time, the result is January 1, 1970 0:0 0 seconds start, to the program execution obtains the system time to elapse the number of milliseconds * 1 seconds =1000 milliseconds * *
  public void Getsystemcurrenttime () {System.out.println ("---get system current time---");
 System.out.println (System.currenttimemillis ());
   public void Getcurrentdate () {System.out.println ("---get system current time---"); 
  Creates and initializes a date (the initial value is current) Date date = new Date (); 
  System.out.println ("Now the date is =" + date.tostring ()); 
 System.out.println ("The number of milliseconds experienced since January 1, 1970 0:0 0 seconds =" + Date.gettime ()); }
}

2, the use of Java.text.DateFormat abstract class
DateFormat is an abstract class of date/time format subclasses that format and parse dates or times in a language-independent way. Date/time formatting subclasses (such as SimpleDateFormat) allow formatting (that is, date-> text), parsing (text-> date), and standardization. Represents a date as a day object, or as a number of milliseconds from GMT (Greenwich Mean Time) 1970, January 1 00:00:00 this moment.
DateFormat provides a number of class methods for obtaining a default date/time Formatter based on the default or given locale and a variety of formatting styles. Formatting styles include full, LONG, MEDIUM, and short. More details and examples of how to use these styles are provided in the method description.
DateFormat can help you format and analyze dates for any locale. For months, weeks, and even calendar formats (lunar and Gregorian), their code is entirely independent of the language environment's conventions.
To format a date in the current locale, you can use a static factory method:

myString = Dateformat.getdateinstance (). Format (mydate);

If you format multiple dates, it is more efficient to get the format and use it multiple times so that the system does not have to get information about the environment language and the country conventions more than once.

 DateFormat df = dateformat.getdateinstance ();
 for (int i = 0; i < mydate.length ++i) {
 output.println (Df.format (mydate[i)) + ";");
 


To format a date for a different locale, you can specify it in the call to Getdateinstance ().
DateFormat df = dateformat.getdateinstance (Dateformat.long, locale.france);
You can also use DateFormat for analysis.
mydate = Df.parse (myString);
Use Getdateinstance to obtain the standard date format for the country. Additional static factory methods are also available. The time format of the country can be obtained using gettimeinstance. Use Getdatetimeinstance to get date and time formats. You can pass different options to these factory methods to control the length of the result (from short to MEDIUM to LONG to full). The exact results depend on the locale, but usually:
Short is entirely numeric, such as 12.13.52 or 3:30pm.
MEDIUM longer, such as the 12, 1952
Long longer, such as January 12, 1952 or 3:30:32pm
Full is fully specified, such as Tuesday, April, 1952 AD, or 3:30:42pm PST.
You can also set the time zone on the format, if you prefer. If you want to exert more control over formatting or analysis (or give users more control), you can try to cast the DateFormat obtained from the factory method to SimpleDateFormat. This applies to most countries; just remember to put it in a try block of code to prevent you from encountering a special format.
You can also use the parseposition and fieldposition parsing and formatting methods to progressively analyze the parts of a string. Align any particular field, or find the location where the string is selected on the screen.
DateFormat are not synchronized. It is recommended that you create separate format instances for each thread. If more than one thread accesses a format at the same time, it must maintain an external synchronization.
3, the use of Java.text.SimpleDateFormat (direct subclass of DateFormat)
SimpleDateFormat is a specific class that formats and analyzes dates in a way that is relevant to the language environment. It allows for formatting (date-> text), parsing (text-> date), and normalization.
SimpleDateFormat allows you to select a pattern for any user-defined date-time format. However, it is still recommended that you create a new date-time formatter through the gettimeinstance, getdateinstance, or getdatetimeinstance in DateFormat. Each of these class methods can return a date/time formatter initialized with the default format pattern. You can modify the format pattern by using the Applypattern method as needed. For more information about using these methods, see DateFormat.

The

date and time mode
date and time format is specified by the date and time pattern string. In a date and time pattern string, the unnamed letters ' a ' to ' Z ' and ' a ' to ' Z ' are interpreted as pattern letters, which are used to represent a date or time string element. The text can be enclosed in single quotes (') to avoid interpretation. "" "represents single quotes. All other characters are not interpreted; they are simply copied to the output string when they are formatted, or they match the input string at parse time.
For more reference information to view the JDK API documentation, here is a comprehensive example:

public class Testdateformat {public static void main (string[] args) throws ParseException {Testdateformat TDF = new
  Testdateformat ();
 Tdf.dateformat (); /** * Test SimpleDateFormat class * @throws parseexception/public void DateFormat () throws parseexception{//Chuang 

  Date date = new Date (); 
  Create a different date format DateFormat df1 = Dateformat.getinstance (); 
  DateFormat DF2 = new SimpleDateFormat ("yyyy-mm-01 hh:mm:ss EE");  DateFormat df3 = dateformat.getdateinstance (Dateformat.full, Locale.china); 
  produce a specified length of date format, different lengths, display the date integrity is also different dateformat df4 = new SimpleDateFormat ("yyyy mm month DD Day hh when mm minute ss sec EE", Locale.china); 
  DateFormat df5 = new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss eeeeee", locale.us); 

  DateFormat Df6 = new SimpleDateFormat ("Yyyy-mm-dd"); 
  Output the date in a different format System.out.println ("-------to export the date in a different format------"); 
  System.out.println ("According to Java default date format, default area:" + df1.format (date)); System.out.println ("Yyyy-mm-dd hh:mm:ss EE in the specified format, system default area:" + DF2. Format (date); 
  SYSTEM.OUT.PRINTLN ("Full mode by date, locale to Chinese:" + df3.format (date)); 
  System.out.println ("according to the specified format yyyy mm month DD Day hh when mm minute SS sec EE, area for Chinese:" + df4.format (date)); 
  System.out.println ("according to the specified format Yyyy-mm-dd hh:mm:ss EE, area for the USA:" + df5.format (date)); 
  
  System.out.println ("YYYY-MM-DD in the specified format, system default region:" + df6.format (date)); 
  Converts a string that matches the format to a date, and if the format does not match, an error date Date1 = Df1.parse ("16-01-24 2:32"); 
  Date date2 = Df2.parse ("2016-01-24 02:51:07 Sunday"); 
  Date date3 = Df3.parse ("Friday, January 24, 2016"); 
  Date date4 = Df4.parse ("January 24, 2016 02:51 18 seconds Sunday"); 
  Date Date5 = Df5.parse ("2016-01-24 02:51:18 Sunday"); 

  Date Date6 = Df6.parse ("2016-01-24"); 
  System.out.println ("-------output converts a string to the result of a date------"); 
  System.out.println (date1); 
  System.out.println (DATE2); 
  System.out.println (Date3); 
  System.out.println (DATE4); 
  System.out.println (DATE5); 
 System.out.println (DATE6);

 }
}

4, Java.util.Calendar (abstract class)
Java.util.Calendar is an abstract class, an abstract representation of system time, which provides a way for a specific moment to transform between a set of calendar fields such as year, MONTH, Day_of_month, HOUR, and so on. and provides methods for manipulating calendar fields, such as getting dates for next week. Instantly available in milliseconds, it is an offset from the 00:00:00.000 (i.e. Greenwich Mean time, January 1, 1970, Gregorian calendar).
Like other locale-sensitive classes, Calendar provides a class method getinstance to get a generic object of this type. The getinstance method of the calendar returns a Calendar object that has been initialized by the current date and time.
An example of a calendar is an abstract representation of the system time, which can be known from the calendar instance to the month's time zone. There is a static method get (int x) in the Calendar class, which allows you to obtain information about some values of the relevant instance (month and week months, etc.). Parameter x is a yield value that is defined in the calendar.

Some traps in the calendar, it's easy to fall down:
1. The calendar week begins in Sunday, with a constant value of 0.
2. The calendar month begins in January, with a constant value of 0.
3. The first day of calendar month is 1.
5, Java.util.GregorianCalendar (direct subclass of calendar)

GregorianCalendar is a specific subclass of calendar that provides a standard calendar system used by most countries in the world. Used in conjunction with the Calendar abstract class.
Here's a comprehensive example of how the Calendar class is used:

public class Testcalendar {public static void main (string[] args) throws ParseException {Testcalendar Testcalendar =
  New Testcalendar ();
  Testcalendar.testcalendar ();
 Testcalendar.testcalendar2 (); 
  public void Testcalendar () {//Create calendar in the way calendar Now1 = Calendar.getinstance (); 
  Calendar now2 = new GregorianCalendar (); 
  Calendar now3 = new GregorianCalendar (2016, 01, 24);  Calendar now4 = new GregorianCalendar (2016, 01, 24, 15, 55); 
  Traps: Calendar month is 0~11 calendar now5 = new GregorianCalendar (2016, 01, 24, 15, 55, 44); 
  Calendar now6 = new GregorianCalendar (locale.us); 

  Calendar now7 = new GregorianCalendar (Timezone.gettimezone ("gmt-8:00")); 
  Sets the calendar now2.settime (new Date ()) with the date and millisecond numbers; 

  System.out.println (NOW2); 
  Now2.settimeinmillis (New Date (). GetTime ()); 


  System.out.println (NOW2); 
  Define the Chinese output format of the date, and the output date simpledateformat df = new SimpleDateFormat ("yyyy mm month DD Day hh when mm minute ss sec E", Locale.china); System.out.println ("Get date Chinese formatted output:" + df.fOrmat (Now5.gettime ())); 

  System.out.println (); 
  System.out.println ("--------through calendar to obtain the date of the month and year, and other relevant information--------"); 
  SYSTEM.OUT.PRINTLN ("Get Year:" + Now5.get (calendar.year)); 
  System.out.println ("Get the month (month is starting from 0):" + now5.get (calendar.month)); 
  System.out.println ("Get Day:" + now5.get (calendar.day_of_month)); 
  System.out.println ("Acquire:" + now5.get (calendar.hour)); 
  SYSTEM.OUT.PRINTLN ("Get cent:" + now5.get (Calendar.minute)); 
  System.out.println ("Get seconds:" + now5.get (Calendar.second)); 
  System.out.println ("Get Morning, Afternoon:" + now5.get (calendar.am_pm)); 
  System.out.println ("Get the week number (week is starting from Sunday):" + now5.get (Calendar.day_of_week)); 

  System.out.println (); 
  System.out.println ("---------General Week Cultural Transformation---------"); 
  String dayofweek[] = {"", "Day", "one", "two", "three", "four", "five", "six"}; 
  SYSTEM.OUT.PRINTLN ("The week of the Now5 object is:" + dayofweek[now5.get (Calendar.day_of_week))); 

  System.out.println (); 
  System.out.println ("---------Cultural transformation---------in the general month"); String months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "NineMonth "," October "," November "," December "}; 
 System.out.println ("The month of the Now5 object is:" + months[now5.get (calendar.month))); 
  public void TestCalendar2 () throws parseexception{//Get the maximum number of days of the current month calendar cal = Calendar.getinstance (); 
  int Maxday=cal.getactualmaximum (calendar.day_of_month); 
  int Minday=cal.getactualminimum (calendar.day_of_month);
  System.out.println (Maxday); 
  Take the last day of the month DateFormat formatter3=new simpledateformat ("yyyy-mm-" +maxday);
  System.out.println (Formatter3.format (Cal.gettime ())); 
  Take the last day of the month DateFormat formatter4=new simpledateformat ("yyyy-mm-" +minday);
  System.out.println (Formatter4.format (Cal.gettime ())); 
  Find the number of days between two dates java.text.SimpleDateFormat format = new Java.text.SimpleDateFormat ("Yyyy-mm-dd"); 
  Java.util.Date begindate= format.parse ("2007-12-24"); 
  Java.util.Date enddate= format.parse ("2007-12-25"); 
  Long day= (Enddate.gettime ()-begindate.gettime ())/(24*60*60*1000); 
  System.out.println ("Days apart =" +day); A year ago the date Java.text.Format formatter5=newJava.text.SimpleDateFormat ("Yyyy-mm-dd"); 
  Java.util.Date todaydate=new java.util.Date (); 
  Long Beforetime= (Todaydate.gettime ()/1000) -60*60*24*365; 
  Todaydate.settime (beforetime*1000); 
  String Beforedate=formatter5.format (todaydate); 
  System.out.println (beforedate);
  Calendar calendar = Calendar.getinstance ();
  Calendar.add (Calendar.year,-1);
  System.out.println (Formatter5.format (Calendar.gettime ()));
  The current week of Monday and Sunday simpledateformat dateformat = new SimpleDateFormat ("YyyyMMdd");
  GregorianCalendar GregorianCalendar = new GregorianCalendar ();
  int dayinweek = Gregoriancalendar.get (Calendar.day_of_week);
  int offset = 0;
  if (Dayinweek = = 1) {//Sunday offset = 6;
  else {//Monday to Saturday offset = dayInWeek-2;
  } gregoriancalendar.add (Gregoriancalendar.day_of_month,-offset);
  String sday = Dateformat.format (Gregoriancalendar.gettime ());
  Gregoriancalendar.add (Gregoriancalendar.day_of_month, 6); String Eday = Dateformat.format (Gregoriancalendar.gettIME ());
  System.out.println ("Monday of this week:" + sday);
 System.out.println ("Sunday of this week:" + eday);

 }
 
}

Third, summary

In Java, dates often have five aspects:
1. Date Created
2, date format display
3, the conversion of the date (mainly with the conversion between the strings)
4, the date of middle age, month, day, time, minutes, seconds, weeks, months, etc. get.
5, the date of the size comparison, date of addition and subtraction.

The above is for you to summarize the Java date Time use method, I hope to help you learn.

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.