java 以毫秒为单位比较日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4025832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparing dates in milliseconds
提问by Milli Szabo
Say I have two date fields receiveDate and currentDate. I want to check if receiveDate was 5 days before currentDate. What I did was to convert the dates in milliseconds and then compare against 5. Is there a better way of doing so? If so, how and why mine is any less better? Thanks.
假设我有两个日期字段 receiveDate 和 currentDate。我想检查接收日期是否比当前日期早 5 天。我所做的是以毫秒为单位转换日期,然后与 5 进行比较。有没有更好的方法呢?如果是这样,我的如何以及为什么不那么好?谢谢。
Method I wrote -
我写的方法 -
private static final double DAY_IN_MILLISECONDS = 86400000;
// Param date is the receivedDate
private long getDaysOld(final Date date) {
Calendar suppliedDate = Calendar.getInstance();
suppliedDate.setTime(date);
Calendar today = Calendar.getInstance();
today.setTime(currentDate);
double ageInMillis = (today.getTimeInMillis() - suppliedDate.getTimeInMillis());
double tempDouble;
if(isEqual(ageInMillis, 0.00) || isGreaterThan(Math.abs(ageInMillis), DAY_IN_MILLISECONDS)) {
tempDouble = ageInMillis / DAY_IN_MILLISECONDS;
} else {
tempDouble = DAY_IN_MILLISECONDS / ageInMillis;
}
long ageInDays = Math.round(tempDouble);
return ageInDays;
}
Then I have something like-
然后我有类似的东西-
long daysOld = getDaysOld(receivedDate) ;
if(daysOld <= 5) {
.... some business code ....
}
采纳答案by Eugene Kuleshov
It can be shortened a lot:
它可以缩短很多:
int daysOld = (System.currentTimeMillis() - date.getTime()) / DAY_IN_MILLISECONDS;
回答by Newtopian
回答by Lavir the Whiolet
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class Test {
private static long DAY_IN_MILLISECONDS = 24 * 60 * 60 * 1000;
public static void main(String[] args) throws Exception {
//
Date currentDate = getGregorianDate(1990, Calendar.JANUARY, 20);
Date receiveDate = getGregorianDate(1990, Calendar.JANUARY, 23);
//
if (getDifferenceBetweenDates(receiveDate, currentDate) < 5 * DAY_IN_MILLISECONDS) {
System.out.println("Receive date is not so old.");
}
else {
System.out.println("Receive date is very old.");
}
}
private static long getDifferenceBetweenDates(Date date1, Date date2) {
return Math.abs(date1.getTime() - date2.getTime());
}
private static Date getGregorianDate(int year, int month, int date) {
Calendar calendar = GregorianCalendar.getInstance();
calendar.set(year, month, date);
return calendar.getTime();
}
}
回答by dogbane
You can't simply subtract and divide by 24*60*60*1000, because of daylight savings (in which a day could have 23 or 25 hours).
由于夏令时(一天可能有 23 或 25 小时),您不能简单地减去和除以 24*60*60*1000。
For example, in the UK the clocks moved forward by one hour on 28/03/2010. The difference between 27/03/2010 and 28/03/2010 shouldbe 1 day, but if you follow that approach you will get 0.
例如,在英国,时钟在 2010 年 3 月 28 日向前移动了一小时。27/03/2010 和 28/03/2010 之间的差异应该是 1 天,但如果您遵循这种方法,您将得到 0。
You need to take the offset into account:
您需要考虑偏移量:
public static long daysBetween(Date dateEarly, Date dateLater) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(dateEarly);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(dateLater);
long endL = cal2.getTimeInMillis() + cal2.getTimeZone().getOffset( cal2.getTimeInMillis() );
long startL = cal1.getTimeInMillis() + cal1.getTimeZone().getOffset( cal1.getTimeInMillis() );
return (endL - startL) / (24 * 60 * 60 * 1000);
}
public static void main(String[] args) throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
Date foo = new Date(2010,02,27);
Date bar= new Date(2010,02,28);
System.out.println(daysBetween(foo,bar)); //prints 1
}
回答by Tom Anderson
This all depends on what "five days" means. If you receive something monday lunchtime, then on saturday afternoon, did you receive it within five days or not? The elapsed time is greater than five days, but the day you received it is five days ago. Think about how you'd answer that question; now thing about how your mother would answer that question. It might not be the same - I would suggest that most people, particularly non-programmers, count the passing of days by the passing of local midnights. Five o'clock on wednesday morning is a day after eleven thirty on tuesday night, even though it's less than a day (less than a quarter of a day!) later.
这一切都取决于“五天”的含义。如果您在星期一午餐时间收到某样东西,那么在星期六下午,您是在五天内收到还是没有收到?已用时间超过五天,但您收到的日期是五天前。想想你会如何回答这个问题;现在关于你妈妈会如何回答这个问题。它可能不一样 - 我建议大多数人,尤其是非程序员,通过当地午夜的过去来计算日子的流逝。星期三早上 5 点是星期二晚上 11 点 30 分之后的一天,即使它晚了不到一天(不到四分之一天!)。
So, i think what you want to do is compare just the dates, not the times. You can do this with Calendar by zeroing all the time fields. Given an arrivedDate and a locale (so you can tell when midnight is), i think this is correct:
所以,我认为你想要做的只是比较日期,而不是时间。您可以通过将所有时间字段归零来使用 Calendar 执行此操作。给定一个到达日期和一个语言环境(这样你就可以知道午夜是什么时候),我认为这是正确的:
Calendar deadline = Calendar.getInstance(locale);
deadline.set(Calendar.HOUR_OF_DAY, 0);
deadline.set(Calendar.MINUTE, 0);
deadline.set(Calendar.SECOND, 0);
deadline.set(Calendar.MILLISECOND, 0);
deadline.add(Calendar.DAY_OF_MONTH, 5);
Calendar arrived = Calendar.getInstance(locale);
arrived.setTime(arrivedDate);
deadline.set(Calendar.HOUR_OF_DAY, 0);
deadline.set(Calendar.MINUTE, 0);
deadline.set(Calendar.SECOND, 0);
deadline.set(Calendar.MILLISECOND, 0);
boolean arrivedWithinDeadline = arrived.compareTo(deadline) <= 0;
You should test that thoroughly before actually using it, though.
不过,您应该在实际使用之前对其进行彻底测试。
回答by Azhar Bandri
Below is my method that returns me exact difference in days,
下面是我的方法,它返回天数的确切差异,
/**
* method to get difference of days between current date and user selected date
* @param selectedDateTime: your date n time
* @param isLocalTimeStamp: defines whether the timestamp d is in local or UTC format
* @return days
*/
public static long getDateDiff(long selectedDateTime, boolean isLocalTimeStamp)
{
long timeOne = Calendar.getInstance().getTime().getTime();
long timeTwo = selectedDateTime;
if(!isLocalTimeStamp)
timeTwo += getLocalToUtcDelta();
long delta = (timeOne - timeTwo) / ONE_DAY;
if(delta == 0 || delta == 1) {
Calendar cal1 = new GregorianCalendar();
cal1.setTimeInMillis(timeOne);
Calendar cal2 = new GregorianCalendar();
cal2.setTimeInMillis(timeTwo);
long dayDiff = cal1.get(Calendar.DAY_OF_MONTH) - cal2.get(Calendar.DAY_OF_MONTH);
return dayDiff;
}
return delta;
}