Convert String dates into Java Date objects [dupli

2019-07-28 11:01发布

问题:

Possible Duplicates:
Calculating difference in dates in Java
How can I calculate a time span in Java and format the output?

Say you were given two dates as strings and they are in this format 8/11/11 9:16:36 PM how would I go about converting them to java Date objects so that I can then calculate the difference between two dates?

回答1:

As long as both times are in GMT/UTC, you can do date1.getTime() - date2.getTime() and then divide the result by 86400000 to get number of days. The rest is probably pretty intuitive.

EDIT -- based on edited question

To convert Strings into dates, use the SimpleDateFormat class.

String yourDateString = "8/11/11 9:16:36 PM";
SimpleDateFormat format =
            new SimpleDateFormat("MM/dd/yy HH:mm:ss a");
Date yourDate = format.parse(yourDateString);


回答2:

The majority of Date's getters are deprecated, replaced with Calendar methods. Here's how you would do it

Date date1, date2; //initialized elsewhere
Calendar day1 = new Calendar();
day1.setTime(date1)

Calendar day2 = new Calendar();
day2.setTime(date2);


int yearDiff, monthDiff, dayDiff, hourDiff, minuteDiff, secondDiff;
yearDiff = Math.abs(day1.get(Calendar.YEAR)-day2.get(Calendar.YEAR));
monthDiff = Math.abs(day1.get(Calendar.MONTH)-day2.get(Calendar.MONTH));
dayDiff = Math.abs(day1.get(Calendar.DAY_OF_YEAR)-day2.get(Calendar.DAY_OF_YEAR));
hourDiff = Math.abs(day1.get(Calendar.HOUR_OF_DAY)-day2.get(Calendar.HOUR_OF_DAY));
minuteDiff = Math.abs(day1.get(Calendar.MINUTE)-day2.get(Calendar.MINUTE));
secondDiff = Math.abs(day1.get(Calendar.SECOND)-day2.get(Calendar.SECOND));

Then you can do whatever you like with those numbers.



回答3:

define a SimpleDateFormat matching your format (the java doc is pretty straighforward), then use the parse method to get a the proper Date object, from which you can easily compute the difference between the two dates. Once you have this difference, the best is probably to compute "manually" the number of days / hours / minutes / seconds, although it might be possible to again use a SimpleDateFormat (or some other formatting mechanism) to display the proper values in a generic way.