比较 Java 中的日期 - 仅年、月和日
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18402698/
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 Java - only years, months and days
提问by kingkong
I'm trying to compare to dates object. Only one problem is that I want to compare just days, month and years.
我正在尝试与日期对象进行比较。只有一个问题是我只想比较天、月和年。
/* toString output
mydate 2013-08-23
current date: Thu Aug 23 14:15:34 CEST 2013
If I compare just days ( 23-08-2013 ) dates are equal, if I'm using .after() .before() methods dates are diffrent.
如果我只比较天 (23-08-2013) 日期是相等的,如果我使用 .after() .before() 方法日期是不同的。
Is there is Java method that compares only days, month, years in easy way or do I have to compare each value ?
是否有 Java 方法可以简单地比较天、月、年,还是我必须比较每个值?
回答by Eric Stein
Unfortunately, date support in the core Java API is very weak. You could use Calendar
to strip time/timezone information from your date. You'd probably want to write a separate method to do that. You could also use the Joda API for date/time support, as it's much better than Java's.
不幸的是,核心 Java API 中的日期支持非常薄弱。您可以使用Calendar
从日期中去除时间/时区信息。您可能想编写一个单独的方法来做到这一点。您还可以使用 Joda API 来支持日期/时间,因为它比 Java 好得多。
回答by LaurentG
No there is nothing in the JDK. You could use some external library as Apache Commons Lang. There is a method DateUtils.isSameDay(Date, Date)
which would do what you are looking for.
不,JDK 中没有任何内容。您可以使用一些外部库作为Apache Commons Lang。有一种方法DateUtils.isSameDay(Date, Date)
可以满足您的要求。
Better would be to avoid to use the Date
of Java and use for instance JodaTime.
最好避免使用Date
Java 并使用例如JodaTime。
回答by Ruchira Gayan Ranaweera
How about this way
这种方式怎么样
String str="2013-08-23";
Date date=new SimpleDateFormat("yyyy-MM-dd").parse(str);
Calendar cal=Calendar.getInstance();
cal.setTime(date);
Calendar calNow=Calendar.getInstance();
if(cal.get(Calendar.YEAR)>calNow.get(Calendar.YEAR)){
// do something
}if(cal.get(Calendar.MONTH)>calNow.get(Calendar.MONTH)){
// do something
}if(cal.get(Calendar.DATE)>calNow.get(Calendar.DATE)){
// do something
}
回答by Sajal Dutta
Joda-Timeis much better and highly recommended. But if you have to use Java api, you can do-
Joda-Time更好,强烈推荐。但是如果你必须使用Java api,你可以这样做-
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(someDate);
c2.setTime(someOtherDate);
int yearDiff = c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
int monthDiff = c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
int dayDiff = c1.get(Calendar.DAY_OF_MONTH) - c2.get(Calendar.DAY_OF_MONTH);
Say to compare only year, you can do-
说只比较年份,你可以做——
if(c1.get(Calendar.YEAR) > c2.get(Calendar.YEAR)){
// code
}
etc.
等等。
回答by Evgeniy Dorofeev
You can try this
你可以试试这个
Date d1= ...
Date d2= ...
long dayInMillis = 24 * 3600 * 1000;
boolean dateEqual = d1.getTime() / dayInMillis == d2.getTime() / dayInMillis;
回答by scottb
The solution to this problem is surprisingly simple. You'll need to begin by parsing your date time strings into Date instants in the Java API (you can use a SimpleDateFormat object to help you do this).
这个问题的解决方法出奇的简单。您需要首先将日期时间字符串解析为 Java API 中的日期瞬间(您可以使用 SimpleDateFormat 对象来帮助您执行此操作)。
If you have two instants in time represented as Dates:
如果您有两个时间瞬间表示为日期:
- Get the representation of both as long integers
- Because all Dates are represented internally in UTC, adjust both to the local time zone by adding or substracting the offsets from GMT +/- DST
- Convert both to an integer count of days (which will include the granularity for comparing years and months)
- Compare them by their natural order; if the integers are equal, the day, month, and year are equal irrespective of local time (assuming, of course, that both Date instants were in the same time zone).
- 获取两个长整数的表示
- 由于所有日期均以 UTC 内部表示,因此通过添加或减去 GMT +/- DST 的偏移量来调整本地时区
- 将两者都转换为整数天数(其中将包括比较年和月的粒度)
- 按它们的自然顺序比较它们;如果整数相等,则无论本地时间如何,日、月和年都相等(当然,假设两个 Date 时刻都在同一时区)。
Presto!
快!
A method for adjusting a Date object to local time and returning it as a decimal count of days in the POSIX Epoch follows:
将 Date 对象调整为本地时间并将其作为 POSIX Epoch 中的十进制天数返回的方法如下:
public static double toLocalDayNumber(Date d, GregorianCalendar gc) {
gc.setTime(d);
long utcDateAsMillisFromEpoch = gc.getTimeInMillis();
long localDateAsMillisFromEpoch = utcDateAsMillisFromEpoch +
gc.get(GregorianCalendar.ZONE_OFFSET) +
gc.get(GregorianCalendar.DST_OFFSET);
return (((double) localDateAsMillisFromEpoch) / (86400.0 * 1000.0);
}
This method takes a Date object d
, and a Java API Calendar object gc
that has been constructed with the local TimeZone of interest.
此方法接受一个 Date 对象d
和一个gc
已使用感兴趣的本地 TimeZone 构造的 Java API Calendar 对象。
回答by Pl4yeR
If you don't want to use external libraries and there is no problem using Calendar you could try something like this:
如果你不想使用外部库并且使用 Calendar 没有问题,你可以尝试这样的事情:
Calendar calendar1= Calendar.getInstance();
Calendar calendar2= Calendar.getInstance();
Date date1 = ...;
Date date2= ...;
calendar1.setTime(date1);
calendar1.set(Calendar.HOUR_OF_DAY, 0);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.MILLISECOND, 0);
calendar2.setTime(date2);
calendar2.set(Calendar.HOUR_OF_DAY, 0);
calendar2.set(Calendar.MINUTE, 0);
calendar2.set(Calendar.SECOND, 0);
calendar2.set(Calendar.MILLISECOND, 0);
calendar1.after(calendar2);
calendar1.before(calendar2);
Not so simple but is something...
不是那么简单,而是...
回答by Rakesh KR
By using Date
only
Date
仅通过使用
SimpleDateFormat cDate1 = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
Date now1 = new Date();
String ccDate1 = cDate1.format(now1);
System.out.println("Date1=="+ccDate1);
SimpleDateFormat cDate2 = new SimpleDateFormat("yyyy-MM-dd HH-mm-sss");
Date now2 = new Date();
String ccDate2 = cDate2.format(now2);
System.out.println("Date2=="+ccDate2);
if(ccDate1.equals(ccDate2))//Get full feature of date
System.out.println("Equal");
else
System.out.println("Not Equal");
if(ccDate1.split(" ")[0].equals(ccDate2.split(" ")[0]))//Comparing Full Date
System.out.println("Equal");
else
System.out.println("Not Equal");
if(ccDate1.split(" ")[0].split("-")[0].equals(ccDate2.split(" ")[0].split("-")[0]))//Comparing YEAR
System.out.println("Equal");
else
System.out.println("Not Equal");
if(ccDate1.split(" ")[0].split("-")[1].equals(ccDate2.split(" ")[0].split("-")[1]))//Comparing MONTH
System.out.println("Equal");
else
System.out.println("Not Equal");
if(ccDate1.split(" ")[0].split("-")[2].equals(ccDate2.split(" ")[0].split("-")[2]))//Comparing DAY
System.out.println("Equal");
else
System.out.println("Not Equal");
回答by user3360429
Date date = new Date();
String str="2013-08-23";
Date date=new SimpleDateFormat("yyyy-MM-dd").parse(str);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
if(cal.get(Calendar.YEAR) == cal1.get(Calendar.YEAR)){
System.out.println("Years are equal");
}
else{
System.out.println("Years not equal");
}
if(cal.get(Calendar.MONTH) == cal1.get(Calendar.MONTH)){
System.out.println("Months are equal");
}
else{
System.out.println("Months not equal");
}
回答by Basil Bourque
tl;dr
tl;博士
I want to compare just days, month and years.
mydate 2013-08-23
current date: Thu Aug 23 14:15:34 CEST 2013
我只想比较天、月和年。
我的日期 2013-08-23
当前日期:2013 年 8 月 23 日星期四 14:15:34 CEST
If you want to capture the current date dynamically.
如果要动态捕获当前日期。
LocalDate.now( // Capture the current date…
ZoneId.of( "Europe/Paris" ) // …as seen by the wall-clock time used by the people of a particular region (a time zone).
)
.isEqual(
LocalDate.parse( "2013-08-23" )
)
Or, for a specific moment.
或者,在特定时刻。
ZonedDateTime.of( // Thu Aug 23 14:15:34 CEST 2013
2013 , 8 , 23 , 14 , 15 , 34 , 0 , ZoneId.of( "Europe/Paris" )
)
.toLocalDate() // Extract the date only, leaving behind the time-of-day and the time zone.
.isEqual(
LocalDate.parse( "2013-08-23" )
)
LocalDate
LocalDate
The bundled java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. As other answers suggested, use a decent date-time libary. That means either:
捆绑的 java.util.Date 和 .Calendar 类是出了名的麻烦。避开它们。正如其他答案所建议的那样,请使用合适的日期时间库。这意味着:
You need to extract a date-only value from your date-time, to ignore the time-of-day. Both Joda-Time and java.time have such a class, coincidentally named LocalDate
.
您需要从日期时间中提取仅日期值,以忽略时间。Joda-Time 和 java.time 都有这样一个类,巧合地命名为LocalDate
.
java.time
时间
The java.timeframework built into Java 8 and later supplants the old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Timeframework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extraproject. See the Tutorial.
Java 8 及更高版本中内置的java.time框架取代了旧的 java.util.Date/.Calendar 类。新类的灵感来自非常成功的Joda-Time框架,作为其继承者,概念相似但重新构建。由JSR 310定义。由ThreeTen-Extra项目扩展。请参阅教程。
ZoneId zoneId = ZoneId.of( "Europe/Paris" );
ZonedDateTime x = ZonedDateTime.of( 2014, 1, 2, 3, 4, 5, 6, zoneId );
ZonedDateTime y = ZonedDateTime.now( zoneId );
Extract and compare the date-only portion of the date-time by calling toLocalDate
.
通过调用 提取和比较日期时间的仅日期部分toLocalDate
。
Boolean isSameDate = x.toLocalDate().isEqual( y.toLocalDate() );
Joda-Time
乔达时间
DateTimeZone timeZoneParis = DateTimeZone.forID( "Europe/Paris" );
DateTime x = new DateTime( 2014, 1, 2, 3, 4, 5, 6, timeZoneParis );
DateTime y = new DateTime( 2014, 6, 5, 4, 3, 2, 1, timeZoneParis );
boolean isXAfterY = x.isAfter( y );
To test equality of the date portion, convert the DateTime objects to a LocalDate
which describes only a date without any time-of-day or time zone (other than a time zone used to decide the date).
要测试日期部分的相等性,请将 DateTime 对象转换为LocalDate
仅描述日期而没有任何时间或时区(用于确定日期的时区除外)的 a。
boolean isSameDate = x.toLocalDate().isEqual( y.toLocalDate() );
If you want to examine the constituent elements, Joda-Time offers methods such as dayOfMonth, hourOfDay, and more.
如果您想检查组成元素,Joda-Time 提供了诸如dayOfMonth、 hourOfDay等方法。