Java time related processing summary _java

Source: Internet
Author: User
Tags current time date1 dateformat datetime locale time and date

1. Calculate the maximum number of days in a January

Copy Code code as follows:

Calendar time=calendar.getinstance ();
Time.clear ();
Time.set (calendar.year,year); Year is int
Time.set (calendar.month,i-1); Note that the Calendar object defaults to 0 by January
int Day=time.getactualmaximum (calendar.day_of_month);//Days of the Month
Note: Before using the Set method, you must clear it, otherwise many of the information will be inherited from the system current time

Conversion of 2.Calendar and date

(1) Calendar conversion to date

Copy Code code as follows:

Calendar cal=calendar.getinstance ();
Date Date=cal.gettime ();

(2) Date converted to Calendar
Copy Code code as follows:

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

3. Format output Date Time (more of this)
Copy Code code as follows:

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

4. Calculation of the week ordinal of a year

(1) Calculate a day is the first week of the year

Copy Code code as follows:

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
Copy Code code as follows:

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

Usage of 5.add () and Roll () (less common)

(1) Add () method

Copy Code code as follows:

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
Copy Code code as follows:

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 circulates within this month, generally using the Add () method;

6. Calculate the number of days between two intervals (this is more common)
(1) Pass into calendar object

Copy Code code as follows:

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 the Date object
Copy Code code as follows:

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) Improving the exact calculation of the number of days separated by the method
Copy Code code as follows:

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 for any time, such as to find out the mailbox within three weeks of received mail (get the current system time-and then get three weeks ago) with the time to match the best fitted into a long to compare
such as: 1 years ago Date (note the millisecond conversion)
Copy Code code as follows:

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 convert to each other (most commonly used)

The string is converted to 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 time--long-comparison

Copy Code code as follows:

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 ask for time

Date of month and week

Copy Code code as follows:

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
Copy Code code as follows:

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

9. Combination of Java and specific databases

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

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

Copy Code code as follows:

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
return dateTime;
}

*method converts the date of a string type to one date (java.sql.Date)
* @param datestring A string that needs to be converted to date
* @return Datatime Date
Copy Code code as follows:

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

Convert from date to timestamp

First method: Using the 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 Nano)

Copy Code code as follows:

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";//used to convert to Java.sql.Date
String stotimestamp = "2005-8-18 14:21:12.123";//For strings converted 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 ();
}
}

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.