如何在Java中比较两个字符串日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25963720/
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
How to compare two string dates in Java?
提问by john
I have two dates in String format like below -
我有两个字符串格式的日期,如下所示 -
String startDate = "2014/09/12 00:00";
String endDate = "2014/09/13 00:00";
I want to make sure startDate should be less than endDate. startDate should not be greater than endDate.
我想确保 startDate 应该小于 endDate。startDate 不应大于 endDate。
How can I compare these two dates and return boolean accordingly?
如何比较这两个日期并相应地返回布尔值?
采纳答案by Makoto
Convert them to an actual Date
object, then call before
.
将它们转换为实际Date
对象,然后调用before
.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd h:m");
System.out.println(sdf.parse(startDate).before(sdf.parse(endDate)));
Recall that parse
will throw a ParseException
, so you should either catch it in this code block, or declare it to be thrown as part of your method signature.
回想一下,这parse
会抛出 a ParseException
,因此您应该在此代码块中捕获它,或者声明将其作为方法签名的一部分抛出。
回答by AlexR
Use SimpleDateFormat
to parse your string representation into instance of Date
. The invoke getTime()
to get milliseconds. Then compare the milliseconds.
用于SimpleDateFormat
将您的字符串表示形式解析为Date
. getTime()
获取毫秒的调用。然后比较毫秒。
回答by Kenny Hung
The simplest and safest way would probably be to parse both of these strings as dates, and compare them. You can convert to a date using a SimpleDateFormat, use the before or after method on the date object to compare them.
最简单和最安全的方法可能是将这两个字符串解析为日期,然后比较它们。您可以使用 SimpleDateFormat 转换为日期,使用日期对象上的 before 或 after 方法来比较它们。
回答by Jean Logeart
Use SimpleDateFormat
to convert to Date
to compare:
使用SimpleDateFormat
转换为Date
比较:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
Date start = sdf.parse(startDate);
Date end = sdf.parse(endDate);
System.out.println(start.before(end));
回答by sid smith
Here is a fully working demo. For date formatting, refer - http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
这是一个完整的演示。有关日期格式,请参阅 - http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Dating {
public static void main(String[] args) {
String startDate = "2014/09/12 00:00";
String endDate = "2014/09/13 00:00";
try {
Date start = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
.parse(startDate);
Date end = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
.parse(endDate);
System.out.println(start);
System.out.println(end);
if (start.compareTo(end) > 0) {
System.out.println("start is after end");
} else if (start.compareTo(end) < 0) {
System.out.println("start is before end");
} else if (start.compareTo(end) == 0) {
System.out.println("start is equal to end");
} else {
System.out.println("Something weird happened...");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
回答by Creditto
public class DateComparision
{
public static void main(String args[]) throws AssertionError, ParseException
{
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
//comparing date using compareTo method in Java
System.out.println("Comparing two Date in Java using CompareTo method");
compareDatesByCompareTo(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
compareDatesByCompareTo(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
//comparing dates in java using Date.before, Date.after and Date.equals
System.out.println("Comparing two Date in Java using Date's before, after and equals method");
compareDatesByDateMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
compareDatesByDateMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
//comparing dates in java using Calendar.before(), Calendar.after and Calendar.equals()
System.out.println("Comparing two Date in Java using Calendar's before, after and equals method");
compareDatesByCalendarMethods(df, df.parse("01-01-2012"), df.parse("01-01-2012"));
compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("04-05-2012"));
compareDatesByCalendarMethods(df, df.parse("02-03-2012"), df.parse("01-02-2012"));
}
public static void compareDatesByCompareTo(DateFormat df, Date oldDate, Date newDate)
{
//how to check if date1 is equal to date2
if (oldDate.compareTo(newDate) == 0)
{
System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
}
//checking if date1 is less than date 2
if (oldDate.compareTo(newDate) < 0)
{
System.out.println(df.format(oldDate) + " is less than " + df.format(newDate));
}
//how to check if date1 is greater than date2 in java
if (oldDate.compareTo(newDate) > 0)
{
System.out.println(df.format(oldDate) + " is greater than " + df.format(newDate));
}
}
public static void compareDatesByDateMethods(DateFormat df, Date oldDate, Date newDate)
{
//how to check if two dates are equals in java
if (oldDate.equals(newDate))
{
System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
}
//checking if date1 comes before date2
if (oldDate.before(newDate))
{
System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
}
//checking if date1 comes after date2
if (oldDate.after(newDate))
{
System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
}
}
public static void compareDatesByCalendarMethods(DateFormat df, Date oldDate, Date newDate)
{
//creating calendar instances for date comparision
Calendar oldCal = Calendar.getInstance();
Calendar newCal = Calendar.getInstance();
oldCal.setTime(oldDate);
newCal.setTime(newDate);
//how to check if two dates are equals in java using Calendar
if (oldCal.equals(newCal))
{
System.out.println(df.format(oldDate) + " and " + df.format(newDate) + " are equal to each other");
}
//how to check if one date comes before another using Calendar
if (oldCal.before(newCal))
{
System.out.println(df.format(oldDate) + " comes before " + df.format(newDate));
}
//how to check if one date comes after another using Calendar
if (oldCal.after(newCal))
{
System.out.println(df.format(oldDate) + " comes after " + df.format(newDate));
}
}
}
OUTPUT
输出
Comparing two Date in Java using CompareTo method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 is less than 04-05-2012
02-03-2012 is greater than 01-02-2012
Comparing two Date in Java using Date's before, after and equals method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 comes before 04-05-2012
02-03-2012 comes after 01-02-2012
Comparing two Date in Java using Calendar's before, after and equals method
01-01-2012 and 01-01-2012 are equal to each other
02-03-2012 comes before 04-05-2012
02-03-2012 comes after 01-02-2012
回答by Atais
I think it could be done much simpler,
我认为它可以做得更简单,
Using Joda Time
使用 Joda 时间
You can try parsing this dates simply:
您可以尝试简单地解析此日期:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm");
DateTime d1 = formatter.parseDateTime(startDate);
DateTime d2 = formatter.parseDateTime(endDate);
Assert.assertTrue(d1.isBefore(d2));
Assert.assertTrue(d2.isAfter(d1));
回答by Basil Bourque
tl;dr
tl;博士
Use modern java.timeclasses to parse the inputs into LocalDateTime
objects by defining a formatting pattern with DateTimeFormatter
, and comparing by calling isBefore
.
使用现代java.time类LocalDateTime
通过使用 定义格式化模式DateTimeFormatter
并通过调用 进行比较来将输入解析为对象isBefore
。
java.time
时间
The modern approach uses the java.timeclasses.
现代方法使用java.time类。
Define a formatting pattern to match your inputs.
定义格式模式以匹配您的输入。
Parse as LocalDateTime
objects, as your inputs lack an indicator of time zone or offset-from-UTC.
解析为LocalDateTime
对象,因为您的输入缺少时区或 UTC 偏移量的指示符。
String startInput = "2014/09/12 00:00";
String stopInput = "2014/09/13 00:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu/MM/dd HH:mm" );
LocalDateTime start = LocalDateTime.parse( startInput , f ) ;
LocalDateTime stop = LocalDateTime.parse( stopInput , f ) ;
boolean isBefore = start.isBefore( stop ) ;
Dump to console.
转储到控制台。
System.out.println( start + " is before " + stop + " = " + isBefore );
See this code run live at IdeOne.com.
2014-09-12T00:00 is before 2014-09-13T00:00 = true
2014-09-12T00:00 早于 2014-09-13T00:00 = true
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Most of the java.timefunctionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.timeclasses.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10、Java SE 11及更高版本 - 标准 Java API 的一部分,具有捆绑实现。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 大部分java.time功能在ThreeTen-Backport中向后移植到 Java 6 & 7 。
- 安卓
- java.time类的更高版本的 Android 捆绑实现。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。
The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
该ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如Interval
,YearWeek
,YearQuarter
,和更多。