Java日期/日历对象字符串,比较 [英] Java Date/Calendar object strings, compare

查看:179
本文介绍了Java日期/日历对象字符串,比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如

2011/06/13 17:52:20

并作为字符串返回。我如何比较这与另一个日期格式化相同的方式。我想确定哪一个大于,小于或等于,对于我正在形成的条件语句。

and being returned as strings. How would I compare this against another date formatted the same way. I want to determine which one is greater than, less than or equal to, for a conditional statement I am forming.

没有重新发明轮子可能已经有一个执行此操作的框架

Without reinventing the wheel (or making several cases) when there might already be a framework for doing this

谢谢!

推荐答案


  • 使用 SimpleDateFormat 来解析

  • 获取的日期对象的code>

    • use SimpleDateFormat to parse
    • use compareTo(..) of the Date objects that are obtained
    • SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      Date date1 = sdf.parse(string1);
      Date date2 = sdf.parse(string2);
      
      int result = date1.compareTo(date2);
      

      结果是(从 java.util.Date documentation):

      The result is (from the java.util.Date documentation):


      如果参数Date等于此日期,则值为0;如果此日期在Date参数之前,则值小于0;如果此日期在Date参数之后,则该值大于0。

      the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

      这篇关于Java日期/日历对象字符串,比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆