Calendar and date (convert)

Source: Internet
Author: User
Tags dateformat

The calendar, date, and dateformat of the Java language constitute a basic but important part of the java standard. Date is a key part of business logic computing. All developers should be able to calculate the future date, customize the display format of the date, and parse the text data into a date object.

Create a date object

Let's see how to create a date object using the current date and time of the system and return a long integer. This time is usually called the system time of the Java Virtual Machine (JVM) host environment.

Import java. util. date;
Public class dateexample1 {
Public static void main (string [] ARGs ){
// Get the system date/time
Date = new date ();
System. Out. println (date. gettime ());
}}

On Saturday, October 11, September 29, 2001, and PM, the above example shows 1001803809710 on the system output device. It is worth noting that we use the date constructor to create a date object. This constructor does not accept any parameters, and this constructor uses system internally. currenttimemillis () method to obtain the date from the system. Now we know how to get the number of milliseconds that have elapsed since January 1, 1970. How can we display the date in a format that the user understands? Java. Text. simpledateformat and its abstract base class java. Text. dateformat are used here.

Custom date data format

Suppose we want to customize the date data format, for example, Saturday-October 29-October 29-October 29. The following example shows how to do this:

Import java. Text. simpledateformat;
Import java. util. date;
Public class dateexample2 {
Public static void main (string [] ARGs ){
Simpledateformat bartdateformat = new simpledateformat ("eeee-Mmmm-dd-YYYY ");
Date = new date ();
System. Out. println (bartdateformat. Format (date ));
}}

You can specify the desired format by passing the format string "Eee-Mmmm-dd-YYYY" to the simpledateformat constructor. The ASCII character in the format string tells the Formatting Function Which part of the date data is displayed. Eeee is a week, Mmmm is a month, DD is a day, and YYYY is a year. The number of characters determines how the date is formatted. If you pass "Ee-mm-dd-yy", the sat-09-29-01 is displayed.

Parses text data into a date object

Suppose we have a text string that contains a formatted date object. We want to parse this string and create a date object from the text date data. We will call the simpledateformat class again with the formatted string "mm-dd-YYYY. But this time, we use formatted parsing instead of generating a text date data. In this example, the text string "9-29-2001" is parsed and a date object with a value of 001736000000 is created.

Import java. Text. simpledateformat;
Import java. util. date;
Public class dateexample3 {
Public static void main (string [] ARGs ){
// Create a date formatter that can parse dates
// The form mm-dd-yyyy.
Simpledateformat bartdateformat = new simpledateformat ("mm-dd-YYYY ");
// Create a string containing a text date to be parsed.
String datestringtoparse = "9-29-2001 ";
Try {
// Parse the text version of the date.
// We have to perform the parse method in
// Try-catch construct in case datestringtoparse
// Does not contain a date in the format we are expecting.
Date = bartdateformat. parse (datestringtoparse );
// Now send the parsed date as a long value
// To the system output.
System. Out. println (date. gettime ());
}
Catch (exception ex ){
System. Out. println (ex. getmessage ());
}
}}

Use standard date formatting procedures

Now that we can generate and parse custom date formats, let's take a look at how to use the built-in formatting process. The method dateformat. getdatetimeinstance () allows us to use several different methods to obtain the standard date formatting process. Below are four built-in date formatting procedures. They include a short, medium, long, and complete date format.

Import java. Text. dateformat;
Import java. util. date;
Public class dateexample4 {
Public static void main (string [] ARGs ){

Date = new date ();
Dateformat required dateformat = dateformat. getdatetimeinstance (
Dateformat. Short, dateformat. Short );
Dateformat mediumdateformat = dateformat. getdatetimeinstance (
Dateformat. Medium, dateformat. Medium );

Dateformat longdateformat = dateformat. getdatetimeinstance (
Dateformat. Long, dateformat. Long );

Dateformat fulldateformat = dateformat. getdatetimeinstance (
Dateformat. Full, dateformat. Full );
System. Out. println (required dateformat. Format (date ));
System. Out. println (mediumdateformat. Format (date ));
System. Out. println (longdateformat. Format (date ));
System. Out. println (fulldateformat. Format (date ));
}
}

Note that two values are passed in each call to getdatetimeinstance: the first parameter is the date style, and the second parameter is the time style. They are all basic data types int (integer ). Considering readability, we use constants provided by the dateformat class: short, medium, long, and full.

When running our example program, it will output the following content to the standard output device:
9/29/01 pm
SEP 29,2001 8:44:45
September 29,2001 8:44:45 EDT
Saturday, September 8:44:45 EDT

Calendar class

Now we can format and create a date object, but how can we set and obtain specific parts of the date data, such as hour, day, or minute? How can we add or subtract values in these parts of the date? The answer is to use the calendar class.

Suppose you want to set, get, and manipulate each part of a date object, for example, one day of a month or one day of a week. To demonstrate this process, we will use the specific subclass Java. util. gregoriancalendar. Consider the example below. It calculates that the tenth Friday below is the 13th day.
Import java. util. gregoriancalendar;
Import java. util. date;
Import java. Text. dateformat;
Public class dateexample5 {
Public static void main (string [] ARGs ){
Dateformat = dateformat. getdateinstance (dateformat. Full );

// Create our Gregorian calendar.
Gregoriancalendar Cal = new gregoriancalendar ();
// Set the date and time of our calendar
// To the system's date and time
Cal. settime (new date ());
System. Out. println ("system date:" + dateformat. Format (Cal. gettime ()));
// Set the day of week to Friday
Cal. Set (gregoriancalendar. day_of_week, gregoriancalendar. Friday );
System. Out. println ("after setting day of week to Friday:" + dateformat. Format (Cal. gettime ()));
Int friday13counter = 0;
While (friday13counter <= 10 ){

// Go to the next Friday by adding 7 days.
Cal. Add (gregoriancalendar. day_of_month, 7 );
// If the day of month is 13 we have
// Another Friday the 13th.
If (Cal. Get (gregoriancalendar. day_of_month) = 13) {friday13counter ++;
System. Out. println (dateformat. Format (Cal. gettime ()));
}
}
}
}

In this example, we have made interesting function calls:

Cal. Set (gregoriancalendar. day_of_week,
Gregoriancalendar. Friday );
And: Cal. Add (gregoriancalendar. day_of_month, 7 );

The set method allows us to adjust our time to Friday by simply setting the day of the week. Note that the constants day_of_week and Friday are used to enhance code readability. The add method allows us to add values to the date, and all the complex calculations of the runyear are automatically processed by this method.

The output result of this example is:
System date: Saturday, September 29,2001

When we set it to Friday, it will become:

Friday, September 28, 2001
Friday, September 13,2002
Friday, December 13,2002
Friday, June 13,2003
Friday, February 13,2004
Friday, August 13,2004
Friday, May 13, 2005
Friday, January 13,2006
Friday, October 13,2006
Friday, Friday, 13,2007
Friday, July 13,2007
Friday, June 13,2008
Time in your hands

With these date and calendar examples, you should be able to use Java. util. Date, java. Text. simpledateformat, and Java. util. gregoriancalendar to create many methods.

Calendar and date (convert)

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.