Detailed explanation of java time and date usage and query code, and detailed explanation of java date code

Source: Internet
Author: User

Detailed explanation of java time and date usage and query code, and detailed explanation of java date code

As long as the format is correct, you can directly compare the string, and the accuracy is the same as that of seconds.

String  s1  =  "2003-12-12  11:30:24";   String  s2  =  "2004-04-01  13:31:40";   int  res  =  s1.compareTo(s2);  

Calculate the date difference

SimpleDateFormat df = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss"); Date begin = df. parse ("11:30:24"); Date end = df. parse ("13:31:40"); long between = (end. getTime ()-begin. getTime ()/1000; // divide by 1000 to convert to int day = between/(24*3600); int hour = between % (24*3600)/3600; int minute = between % 3600/60; int second = between % 60;

The time and date classes are often used, so we will summarize the commonly used date methods and attributes as follows for your convenience

1. Calculate the maximum number of days in a month

Calendar time = Calendar. getInstance (); time. clear (); time. set (Calendar. YEAR, year); time. set (Calendar. MONTH, I-1); // note that the default January Calendar Object is 0 int day = time. getActualMaximum (Calendar. DAY_OF_MONTH); // number of days of the current month

Note: before using the set method, you 'd better clear it first. Otherwise, much information will inherit from the current system time.

2. Conversion of Calendar and Date

(1) convert Calendar to Date

Calendar cal=Calendar.getInstance(); Date date=cal.getTime(); 

(2) convert Date to Calendar

Date date=new Date(); Calendar cal=Calendar.getInstance(); cal.setTime(date); 

3. format the output Date and Time

Date date=new Date(); SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); System.out.println(df.format(date)); 

4. Calculate the week of the year

(1) Calculate the week number of a day in a year.

Calendar cal=Calendar.getInstance(); cal.set(Calendar.YEAR, 2006); cal.set(Calendar.MONTH, 9); cal.set(Calendar.DAY_OF_MONTH, 3); int weekno=cal.get(Calendar.WEEK_OF_YEAR); 

(2) calculate the number of weeks in a 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
(1) add () method

SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd"); Calendar cal=Calendar.getInstance(); cal.set(Calendar.YEAR, 2006); cal.set(Calendar.MONTH, 9); 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-10-03

(2) roll Method

cal.set(Calendar.YEAR, 2006); cal.set(Calendar.MONTH, 9); 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-10-29

2006-10-03

It can be seen that the roll () method loops over the current month, and the add () method is generally used;

6. Calculate the number of days between two arbitrary periods.

(1) upload to the Calendar Object

/*** // ** Calculate the number of days between two periods * @ param startday start time * @ param endday end time * @ return */public int getIntervalDays (Calendar startday, calendar endday )... {// make sure that startday is before endday if (startday. after (endday ))... {Calendar cal = startday; startday = endday; endday = cal;} // obtain the number of milliseconds for the two time periods long sl = startday. getTimeInMillis (); long el = endday. getTimeInMillis (); long ei = el-sl; // return (int) (ei/(1000*60*60*24) based on the number of milliseconds ));}

(2) input Date object

/*** // ** Calculate the number of days between two periods * @ param startday start time * @ param endday end time * @ return */public int getIntervalDays (Date startday, date endday )... {// make sure that startday is before endday if (startday. after (endday ))... {Date cal = startday; startday = endday; endday = cal;} // you can obtain the number of milliseconds for each time. long sl = startday. getTime (); long el = endday. getTime (); long ei = el-sl; // return (int) (ei/(1000*60*60*24) based on the number of milliseconds ));}

Similarly, you can use the same method to calculate the number of hours, minutes, And seconds between two different time periods.
Note: The above method is completely time-based, and sometimes it is not satisfactory, for example:

startday="2006-10-11 20:00:00" endday="2006-10-12 8:00:00" 

The calculation result is 0, but we may change the calculation result to 1. You can use the following method to achieve this:
Before passing parameters, set the endday time, for example:

endday.set(Calendar.HOUR_OF_DAY, 23); endday.set(Calendar.MINUTE, 59); endday.set(Calendar.SECOND, 59); endday.set(Calendar.MILLISECOND, 59); 

In this way, input startday and endday, and the result will be as expected. However, if the above method is too difficult, you can refer to the following method:
(3) improved methods for accurate calculation of days separated

Public int getDaysBetween (Calendar d1, Calendar d2 )... {if (d1.after (d2 ))... {// swap dates so that d1 is start and d2 is end 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); // obtain the actual days of the current year d1.add (Calendar. YEAR, 1);} while (d1.get (Calendar. YEAR )! = Y2);} return days ;}

Obtain the current system time:

Public static String getSystemTime () {Date date = new Date (); SimpleDateFormat df = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss"); return df. format (date);} // convert a string to a time type (the string can be of any type, as long as it is consistent with the format in SimpleDateFormat) 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"); SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss"); String mDateTime1 = formatter. format (d); // the current time. getInstance (); // SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss"); SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss g e d f w W a e f "); String mDateTime = formatter. format (cal. getTime (); // Date 1 year ago 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); // tomorrow's date myDate = new java. util. date (); myTime = (myDate. getTime ()/1000) + 60*60*24; myDate. setTime (myTime * 1000); mDate = formatter. format (myDate); // the number of days between two time periods SimpleDateFormat myFormatter = new SimpleDateFormat ("yyyy-MM-dd"); java. util. date date = myFormatter. parse ("2003-05-1"); java. util. date mydate = myFormatter. parse ("1899-12-30"); long day = (date. getTime ()-mydate. getTime ()/(24*60*60*1000); // Add a half-hour SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd hh: mm: ss "); java. util. date date1 = format. parse ("23:16:00"); long Time = (date1.getTime ()/1000) + 60*30; date1.setTime (Time * 1000); String mydate1 = formatter. format (date1); // obtain the date SimpleDateFormat formatter2 = new SimpleDateFormat ("yyyy-mm f e"); java. util. date date2 = formatter2.parse ("2003-05 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 );

In developing web applications, for different database date types, we need to convert the date types in our programs. If the corresponding database data is of the oracle Date type, that is, only the year, month, and day are required, you can select java. SQL. date type. if it corresponds to the DateTime type of the MSsqlserver database, that is, year, month, day, hour, minute, and second, select java. SQL. timestamp type

You can use dateFormat to define the time and date format and convert it to a string.

Package personal. jessica; import java. util. date; import java. util. calendar; import java. SQL. timestamp; import java. text. dateFormat; import java. text. simpleDateFormat; import java. util. locale; class Datetest {/*** method converts a string-type date into a timestamp (timestamp java. SQL. timestamp) * @ param dateString the string to be converted to timestamp * @ 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 the format // dateFormat = new SimpleDateFormat ("yyyy-MM-dd kk: mm: ss", Locale. ENGLISH); dateFormat. setLenient (false); java. util. date timeDate = dateFormat. parse (dateString); // java of util type. SQL. timestamp dateTime = new java. SQL. timestamp (timeDate. getTime (); // Timestamp type, timeDate. getTime () returns a long type return dateTime;}/*** method to convert a string-type Date into a Date (java. SQL. date) * @ param dateString the string 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); // java of util type. SQL. date dateTime = new java. SQL. date (timeDate. getTime (); // return dateTime of the SQL type;} public static void main (String [] args) {Date da = new Date (); // Note: da. getTime () is a long value System. out. println (da. getTime (); // convert from date to timestamp // Method 1: Use new Timestamp (long) Timestamp t = new Timestamp (new Date (). getTime (); System. out. println (t); // Method 2: 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"; // convert to java. SQL. date String sToTimestamp = "14:21:12. 123 "; // used for conversion to java. SQL. timestamp string Date date1 = string2Date (sToDate); Timestamp date2 = string2Time (sToTimestamp); System. out. println ("Date:" + date1.toString (); // The result shows System. out. println ("Timestamp:" + date2.toString (); // Result Display} catch (Exception e) {e. printStackTrace ();}}}

The following is an example:

Java code

Package test; import java. text. dateFormat; import java. text. parseException; import java. text. simpleDateFormat; import java. util. calendar; import java. util. date; import java. util. hashtable; import javax. swing. JOptionPane; public class Test2 {public static Boolean isdate (String s) {String a [] = s. split ("-"); Boolean flg = true; if (! (Integer. parseint (a [0]) >=1950 & Integer. parseint (a [0]) <= 2050) {flg = false;} return flg;} public static Boolean checkDate (String s) {Boolean ret = true; try {DateFormat df = new SimpleDateFormat ("yyyy-MM-dd"); ret = df. format (df. parse (s )). equals (s);} catch (ParseException e) {ret = false;} return ret;} public Object dateinfo (String s) {String a [] = s. split ("-", 2); Hashtable fest = new Hashtable (); fest. put ("01-01 "," New Year's Day "); fest. put ("02-14", "Valentine's Day"); fest. put ("03-12", "Arbor Day"); fest. put ("03-15", "Consumer Festival"); fest. put ("04-01", "Fool's Day"); fest. put ("04-05", "Tomb Sweeping Day"); fest. put ("05-01", "Labor Day"); fest. put ("06-01", "Children's Day"); fest. put ("07-01", ""); fest. put ("08-01", "Jianjun Festival"); fest. put ("09-10", "Teacher's Day"); fest. put ("10-01", "National Day"); fest. put ("12-25", "Christmas"); if (fest. containsKey (a [1]) {return fest. get (a [1]);} else {return "no holiday";} public String xingzuo (Date s) {Cale Ndar cal = Calendar. getInstance (); cal. setTime (s); String xingzuo = "NONE"; int day = cal. get (Calendar. DAY_OF_YEAR); if (cal. get (Calendar. YEAR) % 4 = 0) & (cal. get (Calendar. YEAR) % 100! = 0) | (cal. get (Calendar. YEAR) % 400 = 0) {if (day> = 1 & day <= 19) | (day> = 357 & day <= 366 )) {xingzuo = "Capricorn";} else if (day >=20 & day <= 49) {xingzuo = "Aquarius ";} else if (day >=50 & day <= 80) {xingzuo = "Pisces";} else if (day >=81 & day <= 110) {xingzuo = "Aries";} else if (day >=111 & day <= 141) {xingzuo = "Taurus ";} else if (day> = 142 & day <= 173) {xingzuo = "Gemini";} else if (day> = 174 & day <= 203) {xingzuo = "cancer";} else if (day >=204 & day <= 235) {x Ingzuo = "Leo";} else if (day >=236 & day <= 266) {xingzuo = "Virgo ";} else if (day> = 267 & day <= 296) {xingzuo = "Libra";} else if (day> = 297 & day <= 326) {xingzuo = "scorpio" ;}else if (day >=327 & day <= 356) {xingzuo = "Sagittarius ";}} else {if (day >=1 & day <= 19) | (day >=357 & day <= 366) {xingzuo = "Capricorn ";} else if (day> = 20 & day <= 48) {xingzuo = "Aquarius";} else if (day> = 49 & day <= 79) {xingzuo = "Pisces";} else if (day >=80 & day <= 109) {xingzuo = "Aries ";} Else if (day> = 110 & day <= 140) {xingzuo = "Taurus";} else if (day> = 141 & day <= 172) {xingzuo = "Gemini" ;}else if (day >=173 & day <= 202) {xingzuo = "cancer ";} else if (day> = 203 & day <= 234) {xingzuo = "Leo";} else if (day> = 235 & day <= 265) {xingzuo = "Virgo";} else if (day >=266 & day <= 295) {xingzuo = "Libra ";} else if (day> = 296 & day <= 325) {xingzuo = "scorpio";} else if (day> = 326 & day <= 355) {xingzuo = "Sagittarius" ;}} return xingzuo;} public Date par SeDate (String s) {SimpleDateFormat bartDateFormat = new SimpleDateFormat ("yyyy-MM-dd"); try {Date date3 = bartDateFormat. parse (s); date3 = bartDateFormat. parse (s); return date3;} catch (Exception ex) {return null;} public static void main (String [] args) {Calendar ar cal = Calendar ar. getInstance (); Test2 test2 = new Test2 (); String date1 = JOptionPane. showInputDialog ("enter a date, for example, 2000-10-15"); while (! (Test2.checkDate (date1) & Test2.isdate (date1) {date1 = JOptionPane. showInputDialog ("Enter the date in the format of 2000-10-15");} SimpleDateFormat bartDateFormat1 = new SimpleDateFormat ("yyyy, MM, dd, EEEE "); simpleDateFormat bartDateFormat2 = new SimpleDateFormat ("yyyy-MM-dd"); Date date2 = test2.parseDate (date1); String festinfo = (String) test2.dateinfo (date1); System. out. println (bartDateFormat1.format (date2) + "," + festinfo + "," + test2.xingzuo (date2); String day = JOptionPane. showInputDialog ("Enter the date information for N Days"); cal. setTime (date2); cal. add (Calendar. DATE, Integer. parseint (day); String date5 = bartDateFormat2.format (cal. getTime (); festinfo = (String) test2.dateinfo (date5); System. out. println (bartDateFormat1.format (cal. getTime () + "," + festinfo + "," + test2.xingzuo (cal. getTime ()));}}

Summary

The above is all the details about the java time and date usage and query code in this article, and I hope to help you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Related Article

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.