Decrement a date in Java

我的未来我决定 提交于 2020-01-01 08:43:46

问题


I want to get the previous day (24 hours) from the current time.

e.g if current time is Date currentTime = new Date();

2011-04-25 12:15:31:562 GMT

How to determine time i.e

2011-04-24 12:15:31:562 GMT


回答1:


You can do that using Calendar class:

Calendar cal = Calendar.getInstance();
cal.setTime ( date ); // convert your date to Calendar object
int daysToDecrement = -1;
cal.add(Calendar.DATE, daysToDecrement);
date = cal.getTime(); // again get back your date object



回答2:


I would suggest you use Joda Time to start with, which is a much nicer API. Then you can use:

DateTime yesterday = new DateTime().minusDays(1);

Note that "this time yesterday" isn't always 24 hours ago though... you need to think about time zones etc. You may want to use LocalDateTime or Instant instead of DateTime.




回答3:


please checkout this here: Java Date vs Calendar

Calendar cal=Calendar.getInstance();
cal.setTime(date); //not sure if date.getTime() is needed here
cal.add(Calendar.DAY_OF_MONTH, -1);
Date newDate = cal.getTime();



回答4:


24 hours and 1 day are not the same thing. But you do both using Calendar:

Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, -1);
Date d = c.getTime();

If you are going back 24 hours, you would use Calendar.HOUR_OF_DAY



来源:https://stackoverflow.com/questions/5799797/decrement-a-date-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!