How to deal with dates in Java

Source: Internet
Author: User
Tags dateformat parse string

(1) Date

* Date:

* Introduction is the date class under the Java.util package, which is responsible for describing data such as dates.

* Date mainly describes the current time millisecond value object.

* Many of its methods are not conducive to internationalization and have been scrapped.

*

* Date is to encapsulate the current millisecond value as a Date object.

* How to turn a millisecond value into a Date object

* Date () It is the millisecond value of the current point of time is converted to a Date object

* Date (long date) turns a millisecond value we specify into a Date object

* SetTime (long time) sets the current date object to the one that corresponds to the specified millisecond value.

*

* How to turn a Date object into millisecond value

* There is a gettime method in the date class that allows you to turn a Date object into a millisecond value

 Public class Datedemo {    publicstaticvoid  main (string[] args) {        // Create a Date object        New Date ();        D.settime (1380000910915L); //         Date D = new Date (1380000910915L);         System.out.println (d);        System.out.println (D.togmtstring ());        System.out.println (D.tolocalestring ());        System.out.println (D.gettime ());}            }
(2) DateFormat

DateFormat class:

This class is located under the Java.text package.

This class is an abstract class, and this class cannot be directly new to the object.

The DateFormat class is mainly to format date objects into string data

The Date object, through the DateFormat class, can be formatted as a string data "Xxxx-xx-xx Hh:mm:ss"

The DateFormat class can also parse a string data into a Date object.

"xxxx-xx-xx hh:mm:ss" resolves to a Date object

Formatting: Formatting objects into text (strings)

Parsing: Turning text (strings) into objects

Because the DateFormat class is an abstract class, it cannot create objects, but this class provides partial static methods that can be used to obtain objects of this class.

The Getdateinstance method has overloads, and you can specify the style when you get the DateFormat object

dateformat.full:2014 Friday, August 22

DATEFORMAT.LONG:2014 year August 22

Dateformat.medium:2014-8-22 is the default style

Dateformat.short:14-8-22

When parsing a string data using the parse method in the DateFormat class, the string data must be given a format that is consistent with the style specified when acquiring the DateFormat object.

This can be resolved, otherwise the parsing fails.

//Use the DateFormat class to parse date data in string form into a Date object     Public Static voidMethod_2 ()throwsParseException {//Date data in string formString time = "Friday, August 22, 2014"; //get DateFormat ObjectDateFormat DF =dateformat.getdateinstance (dateformat.full); //parsing StringsDate d =Df.parse (time);            System.out.println (d); }    //Use the DateFormat class to format dates     Public Static voidmethod_1 () {//get DateFormat Object//DateFormat df = dateformat.getdateinstance (); //DateFormat df = dateformat.getdateinstance (dateformat.short);DateFormat DF =dateformat.getdatetimeinstance (Dateformat.medium,dateformat.medium); //Create a Date objectDate d =NewDate ();        System.out.println (d); //format this Date objectString time =Df.format (d);    System.out.println (time); }
(3) SimpleDateFormat

The subclass SimpleDateFormat of DateFormat can be used when we want to parse string data or format date objects in the style we specify.

/** Demo using SimpleDateFormat format Date Object * "xxxx year xx/xx hh when mm min ss sec"*/     Public Static voidMethod_4 () {//Get Date ObjectDate d =NewDate (); //get formatted ObjectSimpleDateFormat SDF =NewSimpleDateFormat ("yyyy year mm/dd hh mm min ss sec"); //format a Date objectString time =Sdf.format (d);    System.out.println (time); }    /** Demo uses SimpleDateFormat class to resolve specified format data * "2014/08/22" corresponding format: "YYYY/MM/DD" * "2414/08/22 23:23:23" "yyyy/mm/d D HH:mm:ss "*/     Public Static voidMethod_3 ()throwsParseException {//Date data in string formString time = "2414/08/22 23:23:23"; //Create a SimpleDateFormat objectSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy/mm/dd HH:mm:ss"); //parsingDate d =Sdf.parse (time);    System.out.println (d); }
/** Requirement: * There are 2 date data in string form, need to calculate how many days they are apart? * "2014 09/28 23:13 01 Seconds" * "2 September-February 12th 12:02 01 Seconds" * * Idea: * To calculate the number of days, first of all, the string form of the date data into a millisecond value, and then The time difference is obtained by subtracting the millisecond value, and then the number of days apart is then transferred. * How to turn string data into millisecond values? * You can convert a Date object to a millisecond value by using the GetTime method in the Date Object * Convert the string date data to a Date object, which can be done using the SimpleDateFormat class*/ Public classDatetest { Public Static voidMain (string[] args)throwsparseexception {String s1_time= "2014 09/28 23:13 01 Seconds"; String S2_time= "201 March-September 27th 23:13 01 Seconds"; //get the format deviceSimpleDateFormat SDF1 =NewSimpleDateFormat ("yyyy year mm/dd hh mm min ss sec"); SimpleDateFormat SDF2=NewSimpleDateFormat ("Yyyy-mm month DD Day hh mm min ss sec"); //parsing StringsDate D1 =Sdf1.parse (s1_time); Date D2=Sdf2.parse (s2_time); //turns the current date object into a millisecond value        LongTime_1 =D1.gettime (); Longtime_2 =D2.gettime (); LongDay = (Math.Abs (time_1-time_2))/1000/60/60/24;    System.out.println (day); }}

(4) Calendar

Calendar:

Located under the Java.util package.

This class is primarily used to describe calendar data.

The Calendar class is an abstract class that can get its instance through the GetInstance method.

It defines a number of static member variables, the calendar of common years, months, days, minutes, seconds, weeks and other data are encapsulated into static member variables,

Its corresponding data can be obtained directly from the Calendar class.

In the computer the month starts from 0, 0 represents January, 1 means February, and 11 is December.

The week is starting from 0, 0 means Sunday, 1 means Monday

Once we have the calendar instance, we can get all the data encapsulated in the current instance through the Get method in the Calendar class.

When you use the Get method, you need to use the Calendar class itself and the static member variables in it.

In the Calendar class there is a set method, you can change the corresponding data in the calendar instance to the specific date and time we want to specify

The Add method can modify its corresponding data on the specified member variable

 Public classCalendardemo { Public Static voidMain (string[] args) {method_2 (); }        /** How many days in February of any year * * idea: * Get a Calendar instance and set the current month to March 1 by using the Set method.     * Then use the Add method to get the number of days in the current month-1. Then go to get the current number of days, must be the last day of February. */     Public Static voidmethod_2 () {//get a Calendar instanceCalendar C =calendar.getinstance (); //use loops to provide the year         for(intYear = 1998;year<=2100;year++ ){            //use the Set method to set the current month dayC.set (year, 2, 1); //use the Add method to let the number of days-1C.add (Calendar.day_of_month, 1); System.out.println (The February total of "current" +year+ "year" has: "+C.get (calendar.day_of_month)); }    }    //Calendar Method Demo     Public Static voidmethod_1 () {//get a Calendar instanceCalendar C =calendar.getinstance ();        System.out.println (C.get (calendar.year)); //use the Set method to set the month day//C.set ( +,-);C.add (Calendar.year, 1);    System.out.println (C.get (calendar.year)); }}

How to deal with dates in Java

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.