Java date learning Summary

Source: Internet
Author: User

1. Calculate the maximum number of days in a month

Calendar time = calendar. getinstance (); time. clear (); time. set (calendar. year, year); // year is inttime. 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 must clear it first. Otherwise, many 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 (this is usually used)

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 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, 8);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 (not 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 over the current month, and the add () method is generally used;

6. Calculate the number of days between two arbitrary periods (this is usually used)
(1) upload to the 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) input 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) improved methods for accurate calculation of days separated

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); // obtain the actual days of the current year d1.add (calendar. year, 1);} while (d1.get (calendar. year )! = Y2);} return days ;}

Note: The above method can be used to derive any time, for example, to find the email received within three weeks (get the current system time-then get the time three weeks ago) it is best to compare the received time with the long time.
For example, the date 1 year ago (pay attention to millisecond conversion)

   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. Conversion between string, date, and long (most commonly used)

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)
When we take the time span, substring will issue the specific time -- long-Comparison

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. Calculate the time by Time

Year, month, week, and 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);

9. Java and specific database integration

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.

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 timestamppublic final static Java. SQL. timestamp string2time (string datestring) throws Java. text. parseexception {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 converts a string-type date to a date (Java. SQL. date) * @ Param datestring the string to be converted to date * @ return datatime datepublic final static Java. SQL. date string2date (string datestring) throws Java. lang. exception {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 (); first method to convert from date to timestamp: 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 ();}}

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.