开发者

How can I perform arithmetic operation with dates in Java? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How开发者_Python百科 to calculate time difference in java?

Actually I want to subtract two dates in Java. I tried a lot but can't succeed. So anyone please help me.

Date dtStartDate=pCycMan.getStartDate();

Date dtEndDate=pCycMan.getEndDate();

How can I subtract these two Dates?


long msDiff = dtEndDate.getTime() - dtStartDate.getTime()

msDiff now holds the number of milliseconds difference between the two dates. Feel free to use the division and mod operators to convert to other units.


how can i subtract these two Dates?

You can get the difference in milliseconds like this:

dtEndDate.getTime() - dtStartDate.getTime()

(getTime returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.)

However, for this type of date arithmetics the Joda time library, which has proper classes for time durations (Duration) is probably a better option.


To substract to dates you can get them both as longs getTime() and subtract the values that are returned.


Create two Calendar objects from those Dates and then use the add() method (which can be used to subtrade dates too).


There is a framework to work with the date in java... http://joda-time.sourceforge.net/userguide.html take a look, i'm sure that it can help you


long diffInMillis = dtEndDate.getTimeInMillis() -  dtStartDate.getTimeInMillis();


It depends what do you want. To get difference in milliseconds say dtStartDate.getTime() - dtEndDate.getTime().

To get difference in days, hours etc use Calendar class (methods like after, before, compareTo, roll may help).


Use the Calendar class.

Usage:

Calendar c = Calendar.getInstance();
c.setTime(dtStartDate);
int date = c.get(Calendar.YEAR); //int represents the year of the date
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); // int represents dayOfWeek as defined in link.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜