The date class of Java and the Calendar class (common methods)

Source: Internet
Author: User
Tags date1 dateformat locale

http://blog.csdn.net/xiaopihai86/article/details/50827945

1. Using Java.util.Calender to achieve
Calendar calendar=calendar.getinstance ();
Calendar.settime (New Date ());
System.out.println (Calendar.get (Calendar.day_of_month));//Today's date
Calendar.set (Calendar.day_of_month,calendar.get (calendar.day_of_month) +1);//Let date plus 1
System.out.println (Calendar.get (calendar.date));//top of date plus 1

(1) using Java.text.SimpleDateFormat and java.util.Date to achieve
Date D=new date ();
SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-dd");
System.out.println ("Today's Date:" +df.format (d));
System.out.println ("Two days ago Date:" + Df.format (new Date (D.gettime ()-2 * 24 * 60 * 60 * 1000)));
System.out.println ("Date after three days:" + df.format (new Date (D.gettime () + 3 * 24 * 60 * 60 * 1000)));

(2) Calculate the maximum number of days for a January
Calendar time=calendar.getinstance ();
Time.clear ();
Time.set (calendar.year,year); Year is int
Time.set (calendar.month,i-1);///Note that Calendar object default January is 0
int Day=time.getactualmaximum (calendar.day_of_month);//number of days of the month
Note: Before using the Set method, you must clear it, otherwise many of the information will inherit from the current time of the system

Conversion of 2.Calendar and date

(1) Calendar converted to date
Calendar cal=calendar.getinstance ();
Date Date=cal.gettime ();

(2) Date converted to Calendar
Date Date=new date ();
Calendar cal=calendar.getinstance ();
Cal.settime (date);

3. Formatted output date time (this is used more)

Date Date=new date ();
SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-dd hh:mm:ss");
String Time=df.format (date);
System.out.println (time);

4. Calculate the week ordinal of a year

(1) Calculate a day is the first week of the year
Calendar cal=calendar.getinstance ();
Cal.set (Calendar.year, 2006);
Cal.set (Calendar.month, 8);
Cal.set (Calendar.day_of_month, 3);
int Weekno=cal.get (calendar.week_of_year);

(2) Calculate the number of weeks of the year
SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-dd");
Calendar cal=calendar.getinstance ();
Cal.set (Calendar.year, 2006);
Cal.set (calendar.week_of_year, 1);
Cal.set (Calendar.day_of_week, calendar.monday);
System.out.println (Df.format (Cal.gettime ()));
Output:
2006-01-02

5.add () and Roll () usage (less commonly used)

(1) Add () method
SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-dd");
Calendar cal=calendar.getinstance ();
Cal.set (Calendar.year, 2006);
Cal.set (Calendar.month, 8);
Cal.set (Calendar.day_of_month, 3);
Cal.add (Calendar.date,-4);
Date Date=cal.gettime ();
System.out.println (Df.format (date));
Cal.add (Calendar.date, 4);
Date=cal.gettime ();
System.out.println (Df.format (date));
Output:
2006-08-30
2006-09-03
(2) Roll method
Cal.set (Calendar.year, 2006);
Cal.set (Calendar.month, 8);
Cal.set (Calendar.day_of_month, 3);
Cal.roll (Calendar.date,-4);
Date=cal.gettime ();
System.out.println (Df.format (date));
Cal.roll (Calendar.date, 4);
Date=cal.gettime ();
System.out.println (Df.format (date));
Output:
2006-09-29
2006-09-03
It can be seen that the roll () method loops within this month and generally uses the Add () method;

6. Calculate the number of days between two times in the middle of any time (this is more commonly used)
(1) Pass into calendar object
public int getintervaldays (Calendar startday,calendar endday) ... {
if (Startday.after (endday)) ... {
Calendar Cal=startday;
Startday=endday;
endday=cal;
}
Long Sl=startday.gettimeinmillis ();
Long El=endday.gettimeinmillis ();

Long EI=EL-SL;
return (int) (ei/(1000*60*60*24));
}
(2) passing in a Date object

public int getintervaldays (Date startday,date endday) ... {
if (Startday.after (endday)) ... {
Date Cal=startday;
Startday=endday;
endday=cal;
}
Long Sl=startday.gettime ();
Long El=endday.gettime ();
Long EI=EL-SL;
return (int) (ei/(1000*60*60*24));
}
(3) Improve the method of accurately calculating the number of days apart
public int Getdaysbetween (Calendar d1, calendar D2) ... {
if (D1.after (D2)) ... {
Java.util.Calendar swap = D1;
D1 = D2;
D2 = swap;
}
int days = D2.get (calendar.day_of_year)-D1.get (calendar.day_of_year);
int y2 = d2.get (calendar.year);
if (D1.get (calendar.year)! = y2) ... {
D1 = (Calendar) d1.clone ();
Do ... {
Days + = D1.getactualmaximum (calendar.day_of_year);//Get the actual day of the year
D1.add (calendar.year, 1);
} while (D1.get (calendar.year)! = y2);
}
return days;
}
Note: The above method can be derived from any time, such as to find out the mailbox received within three weeks of the mail (get the current system time-and then get three weeks ago time) with the time of the pickup to match the best fit into a long to compare
such as: 1 years ago Date (note the conversion of milliseconds)
Java.util.Date mydate=new java.util.Date ();
Long Mytime= (Mydate.gettime ()/1000) -60*60*24*365;
Mydate.settime (mytime*1000);
String Mdate=formatter.format (mydate);

7. String and Date, Long conversions (most commonly)

The string is converted into a time type (the string can be any type, as long as it is consistent with the format in SimpleDateFormat)
Usually when we take the time span, we will substring out the specific time--long-compare

Java.text.SimpleDateFormat SDF = new Java.text.SimpleDateFormat ("M/dd/yyyy hh:mm:ss a", Java.util.Locale.US);
Java.util.Date d = sdf.parse ("5/13/2003 10:31:37 AM");
Long Dvalue=d.gettime ();
SimpleDateFormat formatter = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
String Mdatetime1=formatter.format (d);

8. Time to find time

Date of month and week
SimpleDateFormat formatter2 = new SimpleDateFormat ("yyyy-mm F E");
Java.util.Date date2= formatter2.parse ("2003-05 5 Friday");
SimpleDateFormat Formatter3 = new SimpleDateFormat ("Yyyy-mm-dd");
String Mydate2=formatter3.format (DATE2);

The day of the week
Mydate= myformatter.parse ("2001-1-1");
SimpleDateFormat formatter4 = new SimpleDateFormat ("E");
String Mydate3=formatter4.format (mydate);

9. Java and specific database integration

In the development of Web applications, for different database date types, we need to make different conversions to the date types in our programs. If the corresponding database data is the date type of Oracle, that is, only the date of the month and day, you can choose to use the Java.sql.Date type, if the corresponding is the datetime type of the MSSQLServer database, that is, the date of the year and seconds, Select Java.sql.Timestamp Type
You can use DateFormat to define the format of the time date, and turn a string to

Class datetest{
*method converts a date of a string type to a Timestamp (timestamp java.sql.Timestamp)
* @param datestring need to convert to timestamp string
* @return datatime Timestamp

Public final static Java.sql.Timestamp String2time (String datestring)
Throws Java.text.ParseException {
DateFormat DateFormat;
DateFormat = new SimpleDateFormat ("Yyyy-mm-dd kk:mm:ss. SSS ", locale.english);//Set format
DateFormat = new SimpleDateFormat ("Yyyy-mm-dd kk:mm:ss", locale.english);
Dateformat.setlenient (FALSE);
Java.util.Date timedate = Dateformat.parse (datestring);//util type
Java.sql.Timestamp dateTime = new Java.sql.Timestamp (Timedate.gettime ()),//timestamp type, Timedate.gettime () returns a long type
return dateTime;
}

*method converts a date of a string type to a datetime (java.sql.Date)
* @param datestring A string that needs to be converted to date
* @return Datatime Date

Public final static Java.sql.Date String2date (String datestring)
Throws Java.lang.Exception {
DateFormat DateFormat;
DateFormat = new SimpleDateFormat ("Yyyy-mm-dd", locale.english);
Dateformat.setlenient (FALSE);
Java.util.Date timedate = Dateformat.parse (datestring);//util type
Java.sql.Date dateTime = new Java.sql.Date (Timedate.gettime ());//sql type
return dateTime;
}

public static void Main (string[] args) {
Date da = new Date ();
Note: This place da.gettime () Gets the value of a long type
System.out.println (Da.gettime ());

Converted from date to timestamp

First method: Use new Timestamp (long)
Timestamp t = new Timestamp (new Date (). GetTime ());
System.out.println (t);

Second method: use timestamp (int year,int month,int date,int hour,int minute,int second,int Nano)
Timestamp tt = new Timestamp (Calendar.getinstance (). Get (
calendar.year)-1900, Calendar.getinstance (). Get (
Calendar.month), Calendar.getinstance (). Get (
Calendar.date), Calendar.getinstance (). Get (
Calendar.hour), Calendar.getinstance (). Get (
Calendar.minute), Calendar.getinstance (). Get (
Calendar.second), 0);
SYSTEM.OUT.PRINTLN (TT);

try {
String stodate = "2005-8-18";//strings used to convert to Java.sql.Date
String stotimestamp = "2005-8-18 14:21:12.123";//strings used to convert to Java.sql.Timestamp
Date date1 = string2date (stodate);
Timestamp date2 = String2time (Stotimestamp);
System.out.println ("Date:" +date1.tostring ());//Results show
System.out.println ("Timestamp:" +date2.tostring ());//Results show
}catch (Exception e) {
E.printstacktrace ();
}
}
}

The date class of Java and the Calendar class (common methods)

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.