Java time string converted to date type and dates difference days calculation

Source: Internet
Author: User

public static void Main (string[] args) throws ParseException {
String strTime1 = "2015-03-01 15:12:25";
SimpleDateFormat formatter = new SimpleDateFormat ("Yyyy-mm-dd hh:MM:ss");
Date date1 = Formatter.parse (strTime1);
String strTime2 = "2015-03-04 15:12:25";
Date date2 = Formatter.parse (strTime2);
int dif = DateDiff (DATE1,DATE2);
System.out.print (DIF);
}

Results: 3

The type of time is consistent (2015-03-01 15:12:25 and "Yyyy-mm-dd Hh:MM:ss")

/**
* Compare Date1-date2 for a few days
*
* @param date1
* @param date2
* @return
*/
public static int DateDiff (date date1, date date2) {
Calendar Cal1 = Calendar.getinstance ();
Calendar Cal2 = Calendar.getinstance ();
Cal1.settime (date1);
Cal2.settime (DATE2);
Long ldate1 = Date1.gettime () + cal1.get (calendar.zone_offset) + cal1.get (calendar.dst_offset);
Long Ldate2 = Date2.gettime () + cal2.get (calendar.zone_offset) + cal2.get (calendar.dst_offset);
Use integer calculation, truncate the decimals
int hr1 = (int) (ldate1/3600000); 60*60*1000
int HR2 = (int) (ldate2/3600000);

int days1 = HR1/24;
int days2 = HR2/24;

int dateDiff = DAYS1-DAYS2;
return DateDiff;
}

Java time string converted to date type and dates difference days calculation

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.