我从一个文本中获取开始日期,并存储在一个字符串变量中。我想将开始日期与当前日期进行比较,即开始日期是否早于当前日期。
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");
}
发布于 2018-10-12 19:51:09
Java Instant
有非常有用的方法来比较两个实例,即isAfter()
和isBefore()
。请参阅此示例:
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)) {
// ...
}
但是,您应该考虑时区。例如,目前时间(Instant.now()
),在世界上大多数地区,是12/10/2018,但是,在一些地方已经是13/10/2018 (萨摩亚),而在其他地方是11/10/2018 (美国小边远岛屿,只剩下一分钟了)。
顺便说一下,我把21/10/2108改成了21/10/2018。
发布于 2018-10-12 20:28:38
您可以使用此代码进行比较,
LocalDate currentDate = LocalDateTime.now().toLocalDate();
String cDate = ""+currentTime.getMonth().toString()+"/"+currentTime.getDayOfMonth().toString()+"/"+currentTime.getYear().toString();
现在cDate将有dd/MM/yyyy格式的日期字符串。因此为了便于比较,您可以使用Date类,
Date dOne = new SimpleDateFormat("dd/MM/yyyy").parse(cDate);
Date dTwo = new SimpleDateFormat("dd/MM/yyyy").parse(effectiveDate);
然后在这两个日期上使用compareTo()方法,
dOne.compareTo(dTwo); // check value of this method
如果两个日期相同,则返回0,
如果小于0表示日期早于参数日期,
如果大于0,则表示日期在参数日期之后。
https://stackoverflow.com/questions/52778751
复制相似问题