Conversion of various time formats in Java

Source: Internet
Author: User

The following classes are commonly used in the time and day periods:

Java. util. date,
Java. util. calendar,
Java. util. gregoraincalendar,
Java. Text. dateformat,
Java. Text. simpledateformat

Java. util. Date:

Indicates a specific moment, accurate to milliseconds
24*60*60 = 86400 seconds a day
Universal Time (UT or UTC), Greenwich Mean Time (GMT), Greenwich Mean Time (GMT), and Universal Time (UT)
Is equal, Greenwich Mean Time (GMT) is the standard "folk" name, and Universal Time (UT) is the same standard
Scientific title. The Difference Between UTC and UT is that UTC is based on atomic clock, and UT is based on astronomical observation.
(The Chinese version of JDK is really good. It's just like the popular science textbooks)

Common constructor methods:

Date ();

Date (long date)

(Long date) indicates from the standard reference time (called "epoch", that is, 1970.1.1
00:00:00 GMT) the number of milliseconds that have elapsed.

Some constructor methods have been deprecated.

The main method is as follows: (describes several frequently-used and detailed query of JDK documents)

Boolean after (date when) test date after this date.

Boolean before (date when) test date before this date.

Object clone () returns a copy of this object

Long gettime () returns the number of milliseconds this object represents after 00:00:00 GMT

Void settime (long time) sets this date object to represent January 1, January 1, 1970
00:00:00 GMT.

String tostring () converts a date object
String: Dow mon dd hh: mm: ss zzz yyyy

Dow is a day in a week (Sun, Mon, Tue, wed, Thu, Fri, SAT ).
Dow is a day in a week (Sun, Mon, Tue, wed, Thu, Fri, SAT ).
Mon is the month (Jan, Feb, MAR, APR, May, Jun, Jul, Aug, SEP,
Oct, Nov, DEC ).

Dd is a day in December 31, January (01 to 31). It is displayed in two decimal places.
HH is the hour of the day (00 to 23), displayed as two decimal numbers.
Mm is the minute (00 to 59) in the hour. It is displayed in two decimal places.
SS is the number of seconds (00 to 61) in minutes. It is displayed in two decimal places. 60, 61 because there is "run second"
Zzz is the time zone (and can reflect the time zone ). The Standard Time Zone abbreviation includes the time zone abbreviation recognized by parse.
If no time zone information is provided, zzz is null, that is, it does not contain any characters at all.
YYYY is the year, which is displayed in four decimal digits.

Use System. currenttimemillis () to obtain the number of milliseconds of the current system time

Java. util. calendar:

The calendar class is an abstract class.

Calendar rightnow = calendar. getinstance ();

You can change the calendar fields in three ways: Set (), add (), and roll ().

Set (F, value) changes the calendar field F to value.
In addition, it sets an internal member variable to indicate that the calendar field F has been changed. Despite calendar Fields
F is changed immediately, but until the next call of get (), gettime (), gettimeinmillis (),
Add () or roll () will re-calculate the time value of the calendar (in milliseconds ). Therefore, multiple calls
Using set () does not trigger unnecessary computing multiple times.

Add (F, Delta) to add Delta to the f field. This is equivalent to calling
Set (F, get (f) + delta)

Roll (F, Delta) adds Delta to the f field, but does not change the larger field.

Java. util. gregoriancalendar:
Gregoriancalendar is a specific subclass of calendar. It provides
Standard calendar system used.

Java. Text. dateformat:
Dateformat is an abstract class of the date/time formatting subclass. It is formatted and
Analysis date or time.

Java. Text. simpledateformat:

Simpledateformat is a type used to format and analyze dates in a language environment-related manner.
It allows formatting (date-> text), analysis (text-> date), and normalization.

Simpledateformat allows you to select any custom date-Time Format mode. However,
We recommend that you use gettimeinstance, getdateinstance, or
Getdatetimeinstance to create a date-Time FormatProgram. Every such class Method
Returns a date/time formatting program initialized in the default format. You can use
The applypattern method to modify the format mode.

The date and time formats are specified by the date and time mode strings.
In the date and time pattern strings, letters 'A' to 'Z' and 'A' to 'Z' without quotation marks'
It is interpreted as a pattern letter used to represent a date or time string element.

 

Reference

Example of letter date or time element representation
G era flag text ad
Year 1996, Y; 96
Month July; Jul; 07 in m
Week number 27 in W years
Number 2 of weeks in the month of W
D. days in the year number 189
D number of days in the month 10
Week number 2 in month F
E. Day of the week text Tuesday; TUE
A am/PM mark text pm
H hours in a day (0-23) number 0
K. hours in a day (1-24) Number 24
Hours in k am/PM (0-11) number 0
Hours (1-12) in h am/PM number 12
The number of minutes in the M hour is 30
Number of seconds in seconds 55
S, milliseconds, number 978
Z Time Zone General Time Zone Pacific Standard Time; PST; GMT-08: 00
Z Time Zone RFC 822 Time Zone-0800

 

 

 

Reference

Date and time mode results
"YYYY. Mm. dd G' at 'hh: mm: ss z" 2001.07.04 ad at 12:08:56 PDT
"Eee, mmm D, ''yy" wed, Jul 4, '01
"H: mm a" 12:08 pm
"HH 'o' clock 'a, ZZZZ" 12 o' clock pm, Pacific Daylight Time
"K: Mm A, Z" 0: 08 pm, PDT
"Yyyyy. Mmmmm. dd ggg hh: Mm AAA" 02001. july.04 ad pm
"Eee, d Mmm yyyy hh: mm: ss z" wed, 4 Jul 2001 12:08:56-0700
"Yymmddhhmmssz" 010704120856-0700
"Yyyy-mm-dd't'hh: mm: Ss. sssz" 2001-07-04t12: 08: 56.235-0700

 

Obtain the number of milliseconds of the current system:

Code
Package org. lokvin. example. calendar;

Public class calendarexample1 {

Public static void main (string [] ARGs ){

Java. util. Date = new java. util. Date ();
// Obtain the number of milliseconds in the current system, from 00:00:00 GMT
Long time = system. currenttimemillis ();
Java. util. Date date1 = new java. util. Date (time );
System. Out. println ("date =" + date. tostring ());
System. Out. println ("millisecond =" + time );
System. Out. println ("date1 =" + date1.tostring ());
}

}

Running result:

Reference

Date = mon Dec 04 16:01:16 CST 2006
Milliscond = 1165219276771
Date1 = mon Dec 04 16:01:16 CST 2006

 

 

Code
Package org. lokvin. example. calendar;

Import java. util. calendar;
Import java. util. gregoriancalendar;

Public class calendarexample2 {

Public static void main (string [] ARGs ){
// Obtain the current date
Calendar calendar = calendar. getinstance ();
Int era = calendar. Get (calendar. era); // 0 = BC, 1 = AD
System. Out. println ("era =" + era );
Int year = calendar. Get (calendar. year); // 2006
System. Out. println ("year =" + year );
Int month = calendar. Get (calendar. month );
// Obtain the current month. 0 .. 11 indicates Jan .. dec.
System. Out. println ("month =" + month); // 0 = jan... 11 = Dec
Int day = calendar. Get (calendar. day_of_month );
System. Out. println ("day of month =" + day); // 1
// Obtain the days of the week from Sun = 1, MON = 2... Sta = 7
Int day_of_week = calendar. Get (calendar. day_of_week );
System. Out. println ("day of week =" + day_of_week );

// Obtain the current time in 12-hour format: Calendar. Hour
Int hour12 = calendar. Get (calendar. hour );
// Obtain AM, PM, 0 = am, 1 = PM
Int ampm = calendar. Get (calendar. am_pm );
System. Out. println ("hour 12 =" + hour12 );
System. Out. println ("am PM =" + ampm); // 0 = am, 1 = PM
// Set the value of calendar. hour_of_day when the current time is 24.
Int hour24 = calendar. Get (calendar. hour_of_day );
System. Out. println ("hour 24 =" + hour24 );


Calendar today = new gregoriancalendar (2006, calendar. December, 4 );
// Calendar. getinstance () obtains a specific time point in milliseconds.
System. Out. println ("calendar =" + calendar. gettime (). tostring ());
// Use new gregoriancalendar (2006, calendar. December, 4)
// In addition to the specified year, month, and day, the generated calendar is 0 (hour, minute, and second = 0)
System. Out. println ("today =" + today. gettime (). tostring ());


}

}

Running result:

Reference

Era = 1
Year = 2006
Month = 11
Day of month = 4
Day of week = 2
Hour 12 = 4
Am PM = 1
Hour 24 = 16
Calendar = mon Dec 04 16:22:42 CST 2006
Today = mon Dec 04 00:00:00 CST 2006

 

Comparison between two dates:

Code
Package org. lokvin. example. calendar;

Import java. util. calendar;
Import java. util. gregoriancalendar;

/*
* Compare the order of two calendar objects
*/
Public class calendarexample3 {

Public static void main (string [] ARGs ){
// Date comparison
Calendar Xmas = new gregoriancalendar (2006, calendar. December, 25 );
Calendar newyear = new gregoriancalendar (2007, calendar. January, 1 );

// Compare two dates
Boolean flag = Xmas. Before (newyear );
System. Out. println ("flag =" + flag );

Flag = Xmas. After (newyear );
System. Out. println ("flag =" + flag );

// Number of milliseconds between two dates
Long timediffmillis = newyear. gettimeinmillis ()-Xmas. gettimeinmillis ();
System. Out. println ("time diff millis =" + timediffmillis );

// Number of seconds between two dates
Long diffsecs = timediffmillis/1000;
System. Out. println ("time diff secs =" + diffsecs );

// The minute of the difference between the two dates
Long diffmins = timediffmillis/(1000*60 );
System. Out. println ("time diff mins =" + diffmins );

// The hour when the two dates are different
Long diffhours = timediffmillis/(1000*60*60 );
System. Out. println ("time diff hours =" + diffhours );

// The Day of the difference between the two dates
Long diffdays = timediffmillis/(1000*60*60*24 );
System. Out. println ("time diff days =" + diffdays );

}

}

Running result:

 

Reference

Flag = true
Flag = false
Time diff milis = 604800000
Time diff secs = 1, 604800
Time diff Min S = 10080
Time diff hours = 168
Time diff days = 7

 

 

Use calendar to calculate the age:

 

Code
Package org. lokvin. example. calendar;

Import java. util. calendar;
Import java. util. gregoriancalendar;

/*
* Age Calculation
*/
Public class calendarexample4 {

Public static void main (string [] ARGs ){
// Create a Calendar Object for the birthday
Calendar birthdate = new gregoriancalendar (1979, calendar. July, 7 );
Calendar today = calendar. getinstance ();
Int age = today. Get (calendar. Year)-birthdate. Get (calendar. year );

// If there is no birthday, age-1
Birthdate. Add (calendar. Year, age );
If (today. Before (birthdate )){
Age --;
}
System. Out. println ("age =" + age );
}

}

Determine whether it is a leap year:

 

Code
Package org. lokvin. example. calendar;

Import java. util. gregoriancalendar;

/*
* Determines whether it is a leap year of a leap.
*/
Public class calendarexample5 {

Public static void main (string [] ARGs ){
// Determine whether to "leap year"
Gregoriancalendar Cal = new gregoriancalendar ();
Boolean isleapyear = Cal. isleapyear (1998 );
System. Out. println ("is leap year 1998 =" + isleapyear );
Isleapyear = Cal. isleapyear (2000 );
System. Out. println ("is leap year 2000 =" + isleapyear );
}
}

Running result:

Reference

Is leap year 1998 = false
Is leap year 2000 = true

 

Time for obtaining other time zones:

Code
Package org. lokvin. example. calendar;

Import java. util. calendar;
Import java. util. gregoriancalendar;
Import java. util. timezone;

/*
* Get the current time of other time zones
*/

Public class calendarexample6 {

Public static void main (string [] ARGs ){

Calendar Cal = new gregoriancalendar ();
Int hour12 = Cal. Get (calendar. hour );
Int hour24 = Cal. Get (calendar. hour_of_day );
System. Out. println ("hour12 in our timezone =" + hour12 );
System. Out. println ("hour24 in our timezone =" + hour24 );

// Obtain the current time of another time zone and obtain the time zone based on zoneid
Calendar caljap = new gregoriancalendar (timezone. gettimezone ("Japan "));
Hour12 = caljap. Get (calendar. hour );
System. Out. println ("hour12 in Japs timezone =" + hour12 );
Hour24 = caljap. Get (calendar. hour_of_day );
System. Out. println ("hour24 in Japs timezone =" + hour24 );

// Obtain the zoneid list
String [] zoneids = timezone. getavailableids ();
For (INT I = 0; I <zoneids. length; I ++ ){
String zoneid = zoneids [I];
System. Out. println ("zone id =" + zoneid );
}
}
}

Running result:

Reference

Hour12 in our timezone = 5
Hour24 in our timezone = 17
Hour12 in Japs timezone = 6
Hour24 in Japs timezone = 18
Zone id = ETC/GMT + 12
Zone id = ETC/GMT + 11
Zone id = MIT
Zone id = pacpacific/Apia
Zone id = pacpacific/midway
...

Format Date:

Code
Package org. lokvin. example. calendar;

Import java. Text. dateformat;
Import java. Text. simpledateformat;
Import java. util. date;

Public class dateforamexample {
Public static void main (string [] ARGs ){
Date rightnow = new date ();
Dateformat format1 = new simpledateformat ("yyyy-mm-dd hh: mm: SS ");
Dateformat format2 = new simpledateformat ("yyyy-mm-dd ");
Dateformat format3 = new simpledateformat ("H: mm ");
Dateformat format4 = new simpledateformat ("YYYY. Mm. dd G' at 'hh: mm: ss z ");
Dateformat format5 = new simpledateformat ("Eee, mmm, DD, ''yyyy ");
Dateformat format6 = new simpledateformat ("YYYY. Mm. dd KK: Mm 'o' clock 'a, ZZZZ ");
Dateformat format7 = new simpledateformat ("yyyyy. Mmmmm. dd ggg hh: Mm AAA ");

System. Out. println ("format1 =" + format1.format (rightnow ));
System. Out. println ("format2 =" + format2.format (rightnow ));
System. Out. println ("format3 =" + format3.format (rightnow ));
System. Out. println ("format4 =" + format4.format (rightnow ));
System. Out. println ("format5 =" + format5.format (rightnow ));
System. Out. println ("format6 =" + format6.format (rightnow ));
System. Out. println ("format7 =" + format7.format (rightnow ));
}

}

Output result:

Reference

Format1 = 2006-12-05 06:12:02
Format2 = 2006-12-05
Format3 = PM
Format4 = 2006.12.05 at 18:12:02 CST
Format5 = Tuesday, July 5, 2006
Format6 = 2006.12.05 o 'clock afternoon, China Standard Time
Format7 = 02006. December a.m.

 

Take the first day of the month:
Java. Text. simpledateformat format = new java. Text. simpledateformat ("yyyy-MM-01 ");
Java. util. Date firstday = new java. util. Date ();
System. Out. println ("the month first day is" + formats. Format (firstday ));
Take the last day of the month:
Calendar Cal = calendar. getinstance ();
Int maxday = cals. getactualmaximum (calendar. day_of_month );
Java. Text. Format formatter3 = new java. Text. simpledateformat ("yyyy-mm-" + maxday );
System. Out. println (formatter3.format (Cal. gettime ()));

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.