JAVA processing date (date) time and introduction to related classes __java

Source: Internet
Author: User
Tags dateformat iso 8601 locale ranges time and date

JAVA common date and time methods:

1. java.util.Calendar

The Calendar class is an abstract class that provides methods for converting between a specific moment and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, etc., and provides some methods for manipulating calendar fields (such as getting the date of next week) method. Moments can be expressed in milliseconds, which is the offset from the epoch (that is, the Gregorian calendar at 00: 00: 00.000, January 1, 1970 GMT).

example:

Calendar cal = Calendar.getInstance (); // Get a calendar using the default time zone and locale.
cal.add (Calendar.DAY_OF_MONTH, -1); // take the day before the current date.

cal.add (Calendar.DAY_OF_MONTH, +1); // take the day after the current date.

 

// Output the date by formatting
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat ("yyyy-MM-dd");

System.out.println ("Today is:" + format.format (Calendar.getInstance (). GetTime ()));

 

System.out.println ("yesterday is:" + format.format (cal.getTime ()));

Get 2007-12-25 date:

Calendar calendar = new GregorianCalendar (2007, 11, 25,0,0,0);
Date date = calendar.getTime ();
System.out.println ("2007 Christmas is:" + format.format (date));

// java month is from 0-11, and the month should be reduced by 1.

// GregorianCalendar constructor method parameters are: year, month-1, day, hour, minute, second.

Take the part of the date:

int year = calendar.get (Calendar.YEAR);

int month = calendar.get (Calendar.MONTH) +1;

int day = calendar.get (Calendar.DAY_OF_MONTH);

int hour = calendar.get (Calendar.HOUR_OF_DAY);

int minute = calendar.get (Calendar.MINUTE);

int seconds = calendar.get (Calendar.SECOND);

Add 1 to the month.

Determine the maximum number of days in the current month:
Calendar cal = Calendar.getInstance ();
int day = cal.getActualMaximum (Calendar.DAY_OF_MONTH);
System.out.println (day);

2. java.util.Date

The class Date represents a specific instant, accurate to the millisecond. Starting with JDK 1.1, you should use the Calendar class to convert between date and time fields, and use the DateFormat class to format and parse date strings. The corresponding method in Date is deprecated.

Although the Date class is intended to reflect Coordinated Universal Time (UTC), it cannot be so accurate, depending on the host environment of the Java virtual machine. Almost all current operating systems assume 1 day = 24 × 60 × 60 = 86400 seconds. But for UTC, an extra second occurs approximately every two years, called a "leap second." Leap seconds always increase as the last second of the day, and always increase on December 31 or June 30. For example, the last minute in 1995 was 61 seconds because leap seconds were added. Most computer clocks are not particularly accurate and therefore do not reflect the difference in leap seconds.

Some computer standards are defined in Greenwich Mean Time (GMT). Greenwich Mean Time and Universal Time (UT) are equivalent. GMT is the standard "civilian" name; UT is the "standard" name of the same standard. The difference between UTC and UT is that UTC is based on an atomic clock and UT is based on celestial observation. The two are difficult to distinguish in practical applications. Because the rotation of the earth is not uniform (it decelerates and accelerates in complex ways), the UT never flows uniformly. Leap seconds are introduced as needed to keep UTC within 0.9 seconds of UT1, which is a version of UT with some corrections applied. There are other time and date systems; for example, the time scale used by satellite-based Global Positioning System (GPS) is synchronized with UTC, but is not adjusted for leap seconds. An interesting source for more information is the U.S. Naval Observatory, and specifically the Directorate of Time website:

     http://tycho.usno.navy.mil

 

And their definition of "Systems of Time" at:

     http://tycho.usno.navy.mil/systime.html

 

In all methods of class Date that can accept or return year, month, date, hour, minute, and second values, the following representation will be used:

The year y is represented by the integer y-1900.

Months are represented by integers from 0 to 11; 0 is January, 1 is February, and so on; so 11 is December.

The date (day of the month) is represented in the usual way by the integers 1 to 31.

The hour is represented by an integer from 0 to 23. Therefore, the time from midnight to 1 a.m. is 0 o'clock, and the time from noon to 1 p.m. is 12 o'clock.

Minutes are usually represented by integers from 0 to 59.

Seconds are represented by integers from 0 to 61; the values 60 and 61 occur only for leap seconds, although they are only used in Java implementations that actually track leap seconds correctly. Because leap seconds are currently introduced, it is extremely unlikely that two leap seconds will occur in the same minute, but this specification follows ISO C date and time conventions.

In all cases, the parameters assigned to the methods for these purposes need not be within the specified range; for example, you can specify the date as January 32 and interpret it as the same meaning as February 1.

java.util.Date today = new java.util.Date ();
System.out.println ("Today is" + formats.format (today));

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 ()));

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 = (date.getTime ()-mydate.getTime ()) / (24 * 60 * 60 * 1000);
System.out.println ("Number of days separated =" + day);
A year ago:
java.text.Format formatter = new java.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 = formatter.format (todayDate);
System.out.println (beforeDate);
Date after one year:
java.text.Format formatter = new java.text.SimpleDateFormat ("yyyy-MM-dd");
java.util.Date todayDate = new java.util.Date ();
long afterTime = (todayDate.getTime () / 1000) + 60 * 60 * 24 * 365;
todayDate.setTime (afterTime * 1000);
String afterDate = formatter.format (todayDate);
System.out.println (afterDate);

Find the time after 10 hours
java.util.Calendar Cal = java.util.Calendar.getInstance ();
Cal.setTime (dateOper);
Cal.add (java.util.Calendar.HOUR_OF_DAY, 10);
System.out.println ("date:" + forma.format (Cal.getTime ()));

Find the time 10 hours ago

java.util.Calendar Cal = java.util.Calendar.getInstance ();
Cal.setTime (dateOper);
Cal.add (java.util.Calendar.HOUR_OF_DAY, -10);
System.out.println ("date:" + forma.format (Cal.getTime ()));

3.java.sql.Date
Inherited from java.util.Date, is a date type for operating the database

A thin wrapper that wraps millisecond values, which allows JDBC to identify millisecond values as SQL DATE values. The millisecond value represents the number of milliseconds that have passed since January 1, 1970, 00:00:00 GMT. To be consistent with the definition of SQL DATE, the millisecond value wrapped by a java.sql.Date instance must be "normalized" by setting the time, minutes, seconds, and milliseconds to zero in the specific time zone associated with the instance.

 java.sql.Date sqlDate = new java.sql.Date (java.sql.Date.valueOf ("2007-12-25"). getTime ());
Date comparison: simple comparison can be directly compared as a string, or you can use
java.sql.Date.valueOf ("2007-03-08"). compareTo (java.sql.Date.valueOf ("2007-03-18")) method to compare the size of dates. You can also use java.util Date.after (java.util.Date) to compare.

 

4. java.util.GregorianCalendar

  GregorianCalendar is a concrete subclass of Calendar that provides a standard calendar system used in most countries in the world.

GregorianCalendar is a hybrid calendar in a single Supports both the Julian calendar and the Gregorian calendar system with intermittent support. By default, it corresponds to the Gregorian calendar date when the Gregorian calendar was created (in some countries on October 15, 1582 Founded later in other countries). The start date can be changed by the caller by calling setGregorianChange ().

Historically, in those countries that first adopted the Gregorian calendar, October 4, 1582 (Julian calendar) was followed by October 15, 1582 (Gregory calendar). This calendar correctly simulates these changes. Before starting the Gregorian calendar, GregorianCalendar implemented the Julian calendar. The only difference between the Gregorian calendar and the Julian calendar is the leap year rule. The Julian calendar designates leap years every 4 years, while the Gregorian calendar ignores century years that are not divisible by 400.

GregorianCalendar achieves the expected Gregorian and Julian calendars. That is, the date can be calculated by extrapolating the current rule backward or forward in time infinitely. Therefore, for all years, you can use GregorianCalendar to produce meaningful and consistent results. However, with modern Julian calendar rules, the dates obtained using GregorianCalendar are historically accurate only after March 1, 4 AD. Before this date, the application of the leap year rule had no regularity, and before 45 BC, there was not even a Julian calendar.

Before the Gregorian calendar, the new year was March 25. To avoid confusion, this calendar always uses January 1st as the new year. If you want dates before the Gregorian calendar transition and between January 1st and March 24th, you can make manual adjustments.

The calculated value for the WEEK_OF_YEAR field ranges from 1 to 53. The first week of the year begins on the earliest 7 days of getFirstDayOfWeek () and contains at least the days of the year of getMinimalDaysInFirstWeek (). It depends on the values of getMinimalDaysInFirstWeek (), getFirstDayOfWeek (), and the day of the week on January 1. Weeks between the first week of the year and the first week of the next year are numbered sequentially from 2 to 52 or 53 (as needed).

For example, January 1, 1998 is Thursday. If getFirstDayOfWeek () is MONDAY and getMinimalDaysInFirstWeek () is 4 (these values reflect ISO 8601 and many national standards), the first week of 1998 begins on December 29, 1997 and ends on 1998 4th. However, if getFirstDayOfWeek () is SUNDAY, the first week of 1998 begins on January 4, 1998 and ends on January 10, 1998; the first three days of 1998 are part of the 53rd week of 1997.

The calculated value for the WEEK_OF_MONTH field ranges from 0 to 6. The first week of the month (the date of WEEK_OF_MONTH = 1) is the earliest day of at least consecutive getMinimalDaysInFirstWeek () days in the month and ends the day before getFirstDayOfWeek (). Unlike the first week of the year, the first week of a month may be shorter than 7 days and does not have to start on the day of getFirstDayOfWeek () and does not include the date of the previous month. WEEK_OF_MONTH for the month before the first week is 0.

5. java.text.DateFormat
DateFormat is an abstract class for date / time formatting subclasses that formats and parses dates or times in a language-independent manner. Date / time formatting subclasses (such as SimpleDateFormat) allow formatting (that is, date-> text), analysis (text-> date), and normalization. Represents a date as a Date object, or as the number of milliseconds since the moment on January 1, 00:00:00 GMT (Greenwich Mean Time).

DateFormat provides many class methods to obtain a default date / time Formatter based on the default or given locale and multiple formatting styles. Formatting styles include FULL, LONG, MEDIUM, and SHORT. More details and examples of using these styles are provided in the method description.

DateFormat helps format and analyze dates in any locale. For months, weeks, and even calendar formats (Lunar and Gregorian), the code can be completely independent of locale conventions.

To format a date in the current locale, use a static factory method:

  myString = DateFormat.getDateInstance (). format (myDate);

 

If you format multiple dates, it is more efficient to obtain the format and use it multiple times, so that the system does not have to fetch information about environmental languages and country conventions multiple times.

  DateFormat df = DateFormat.getDateInstance ();

  for (int i = 0; i <myDate.length; ++ i) {

    output.println (df.format (myDate [i]) + ";");

  }

 

To format a date in a different locale, specify it in a 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 get the standard date format for the country. There are also other static factory methods provided. Use getTimeInstance to get the time format for that country. Use getDateTimeInstance to get the date and time format. Different options can be passed into these factory methods to control the length of the results (from SHORT to MEDIUM to LONG to FULL). The exact result depends on the locale, but usually:

SHORT is completely numeric, such as 12.13.52 or 3:30 pm

MEDIUM is longer, such as Jan 12, 1952

LONG is longer, such as January 12, 1952 or 3:30:32 pm

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.