Two date-time comparison methods in Java

Source: Internet
Author: User
Tags date1 dateformat

In Java, the comparison time or date is basically converted to date type, this article mainly provides three methods, CompareTo, GetTime, after; also provides a method for calculating the number of days between two days and the date of day after the current day.

Package Com.raipeng.test;import Java.text.dateformat;import Java.text.parseexception;import Java.text.simpledateformat;import Java.util.calendar;import Java.util.date;public class TestTime {public static void Main (string[] args) {//TODO auto-generated method stubstring firsttime = "2015-01-07 08:52"; String secondtime = "2015-01-07 11:53"; Comparedatetime (Firsttime, secondtime); String thirdtime = "2015-01-07 08:52"; String fourthtime = "2015-01-07 12:53"; Comparedatetime (Thirdtime, fourthtime); String fifthtime = "2015-01-07 08:52"; String sixthtime = "2015-01-07 13:53"; Comparedatetime (Fifthtime, sixthtime); String date1 = "2014-12-03"; String date2 = "2015-01-07"; System.out.println ("days = =" +daysbetween (date1, date2)); System.out.println ("after day = =" +getspecifieddayafter (date1));} public static Boolean Comparedatetime (String time1, String time2) {Boolean isfirstbig = False;dateformat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd hh:mm"); try {Date date1 = Dateformat.parse (time1);D ate date2 = DateFormat. Parse (time2); System.out.println ("date1==" +date1.gettime ()); System.out.println ("date2==" +date2.gettime ());//Method 1if (Date1.gettime () > Date2.gettime ()) { System.out.println ("m1--date1 after Date2"); isfirstbig = true;} else if (Date1.gettime () < Date2.gettime ()) {System.out.println ("m1--date1 before Date2"); isfirstbig = false;} Method 2if (Date1.compareto (date2) = = 1) {System.out.println ("m2--date1 after Date2"); isfirstbig = true;} else if (date1.ge Ttime () < Date2.gettime ()) {System.out.println ("m2--date1 before Date2"); isfirstbig = false;} Method 3Calendar cal1 = Calendar.getinstance (); Calendar Cal2 = Calendar.getinstance (); Cal1.settime (date1); Cal2.settime (date2); if (Cal1.after (Cal2)) { System.out.println ("m3--date1 after Date2");} else {System.out.println ("m3--date1 before Date2");}} catch (Exception Exception) {exception.printstacktrace ();} return isfirstbig;} /** * Calculates the number of days between two days * @param startstr * @param endstr * @return */public static int Daysbetween (string startstr, String endstr ) {int daysbetween =0;try {SimpleDateFormat SDF = new SimpleDateFormat ("YYYY-MM-DD");D ate date1 = Sdf.parse (STARTSTR); Calendar startdate = Calendar.getinstance (); Startdate.settime (date1);D ate date2 = Sdf.parse (ENDSTR); Calendar endDate = Calendar.getinstance (); Enddate.settime (Date2); Calendar date = (Calendar) Startdate.clone (); while (Date.before (endDate)) {Date.add (calendar.day_of_month, 1); daysbetween++;}} catch (ParseException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return daysbetween;} /** * Get the day after the specified date * * @param specifiedday * @return * */public static String Getspecifieddaya          fter (String specifiedday) {Calendar c = calendar.getinstance ();          Date date = null;          try {date = new SimpleDateFormat ("Yy-mm-dd"). Parse (Specifiedday);          } catch (ParseException e) {e.printstacktrace ();          } c.settime (date);          int day = C.get (calendar.date);        C.set (calendar.date, day + 1);    String dayafter = new SimpleDateFormat ("Yyyy-mm-dd"). Format (C.gettime ());      return dayafter; }  }



The code is simple, but careless I spent nearly half a day on it.

Problem Description: As above, there are three groups of time pairs, of which the second group of the second time is more than 12, before the change, only the return of the group is wrong, debugging half a day can not find the reason, and then a netizen suggested the value of gettime print out to see, After the call to find more than 12 points back to a long value is indeed much smaller than the other several, and then the month and day to remove the direct comparison of time or the same result, and then suddenly realized that it might be "when" the problem of the unit, and then saw this line of code

DateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd hh:mm");
Subconsciously change this line of code to
DateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd hh:mm");
See the difference is only the case of H, and then the result is correct.

Then in the blog Park to see such an article click the Open link

{0:YYYY-MM-DD HH:MM:SS.FFF}: Date formatted with 24-hour format
{0:YYYY-MM-DD HH:MM:SS.FFF}: Date formatted with 12-hour format

The original is the 24-hour system and 12-hour format difference, so we should pay attention to

The same calendar.hour_of_day and Calendar.hour_of_day, the former is 24 hours, the latter is 12 hours

The above Java code runs after the console output is as follows:


Two date-time comparison methods 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.