[英]Java how to do Calendar comparison
I am taking start date from one text and storing in one string variable. 我从一个文本开始日期并存储在一个字符串变量中。 I want to compare that start date with the current date ie start date is earlier than the current date or not. 我想将该开始日期与当前日期进行比较,即开始日期早于当前日期。
public static void main(String[] rags) throws ParseException{
String total= "I am Going to join in scholl at 21/10/2108";
String[] effectiveDateText=total.split(" ");
String effectiveDate=effectiveDateText[effectiveDateText.length-1];
System.out.println(effectiveDate);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar today = Calendar.getInstance();
String todate=sdf.format(today.getTime());
System.out.println(todate);
if(effectiveDate<todate){
System.out.println("effective date is less then the previous date");
}
Use modern LocalDate
class. 使用现代的LocalDate
类。
LocalDate.parse( // Represent a date-only value without time-of-day and without time zone in `java.time.LocalDate` class.
"I am Going to join in scholl at 21/10/2108". // Split your input string, looking for last part separated by a SPACE.
.substring(
"I am Going to join in scholl at 21/10/2108".lastIndexOf( " " )
+ 1
)
,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Specify formatting pattern to match your input. Tip: Use ISO 8601 formats instead.
)
.toString() // Generate text in standard ISO 8601 format.
2108-10-21 2108-10-21
First split the string into pieces. 首先将字符串切成小段。
String input = "I am Going to join in scholl at 21/10/2108";
String[] parts = input.split( " " );
Look at those parts. 看那些部分。
for ( String part : parts ) {
System.out.println( part );
}
I 一世
am 上午
Going 要去
to 至
join 加入
in 在
scholl cho
at 在
21/10/2108 2108年10月21日
Extract the last part. 提取最后一部分。
String part = parts[ parts.length - 1 ]; // Subtract 1 for index (annoying zero-based counting).
LocalDate
The modern approach uses the java.time classes. 现代方法使用java.time类。 Specifically, LocalDate
for a date-only value without time-of-day and without time zone or offset-from-UTC. 具体来说, LocalDate
用于仅包含日期的值,没有日期时间,没有时区或UTC偏移量。
Parse that last part as a LocalDate
. 将最后一部分解析为LocalDate
。 Define a formatting pattern to match. 定义要匹配的格式模式。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( part , f );
Whenever possible, do not exchange date-time values textually using formats intended for presentation to humans. 只要有可能,就不要使用旨在呈现给人类的格式在文本上交换日期时间值。
Instead, use formats defined for the purpose of data-interchange in the ISO 8601 standard. 相反,请使用ISO 8601标准中为数据交换而定义的格式。 For a date-only value, that would be: YYYY-MM-DD 对于仅日期的值,它将是:YYYY-MM-DD
The java.time classes use the ISO 8601 formats by default when parsing/generating text. 解析/生成文本时, java.time类默认使用ISO 8601格式。
String output = LocalDate.now().toString()
2018-01-23 2018-01-23
The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
. 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.Date
, Calendar
和SimpleDateFormat
。
The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 。 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 . 规格为JSR 310 。
You may exchange java.time objects directly with your database. 您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later. 使用与JDBC 4.2或更高版本兼容的JDBC驱动程序 。 No need for strings, no need for java.sql.*
classes. 不需要字符串,不需要java.sql.*
类。
Where to obtain the java.time classes? 在哪里获取java.time类?
The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more . 您可以在这里找到一些有用的类,比如Interval
, YearWeek
, YearQuarter
,和更多 。
You shoud parse your dates into the Date format and the use the provided methods like this: 您应该将日期解析为Date格式,并使用提供的方法如下:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = sdf.parse("21/10/2108");
Date date2 = sdf.parse("20/01/2018");
System.out.println("date1 : " + sdf.format(date1));
System.out.println("date2 : " + sdf.format(date2));
// after
if (date1.after(date2)) {
}
// before
if (date1.before(date2)) {
}
nice to know: You should be carefull if you what to use date1.equals(date2) since this works on milliseconds precision aswell so you have to use a date delta if you allow user to enter time values in the future. 很高兴知道:如果要使用date1.equals(date2),则应格外小心,因为它也可以毫秒级精度工作,因此,如果允许用户将来输入时间值,则必须使用日期增量。
A Java Instant
has very useful methods to compare two instant with each other, namely isAfter()
and isBefore()
. Java Instant
具有非常有用的方法来将两个即时进行比较,即isAfter()
和isBefore()
。 See this example: 请参阅以下示例:
String total = "I am Going to join in scholl at 21/10/2018";
String[] effectiveDateText = total.split(" ");
String effectiveDate = effectiveDateText[effectiveDateText.length - 1];
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Instant joinDate = sdf.parse(effectiveDate).toInstant();
if (Instant.now().isAfter(joinDate)) {
// ...
}
You should however consider timezones. 但是,您应该考虑时区。 For instance, at present time ( Instant.now()
), at most parts in the world, it's 12/10/2018, at some however, it's already 13/10/2018 (Samoa), and at others it's 11/10/2018 (the US Minor Outlying Islands, only one minute left). 例如,目前( Instant.now()
)在世界上大多数地方是12/10/2018,但是在某些地方已经是13/10/2018(萨摩亚),在其他地方是11/10 / 2018(美国本土外小岛屿,仅剩一分钟)。
BTW, I changed 21/10/2108 to 21/10/2018. 顺便说一句,我将21/10/2108更改为21/10/2018。
You can use this code for comparison, 您可以使用此代码进行比较,
LocalDate currentDate = LocalDateTime.now().toLocalDate();
String cDate = ""+currentTime.getMonth().toString()+"/"+currentTime.getDayOfMonth().toString()+"/"+currentTime.getYear().toString();
Now cDate will have date string in format of dd/MM/yyyy. 现在cDate将具有日期字符串,格式为dd / MM / yyyy。 So for comaparison you can use Date class, 因此,为了进行比较,您可以使用Date类,
Date dOne = new SimpleDateFormat("dd/MM/yyyy").parse(cDate);
Date dTwo = new SimpleDateFormat("dd/MM/yyyy").parse(effectiveDate);
then use compareTo() method on both the dates, 然后在两个日期上使用compareTo()方法,
dOne.compareTo(dTwo); // check value of this method
This return 0 if both dates are same, 如果两个日期相同,则返回0,
if less than 0 means Date is before the argument date, 如果小于0表示Date在参数日期之前,
if greater than 0 means Date is after the argument date. 如果大于0则表示Date在参数日期之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.