简体   繁体   English

我有一个日期(字符串),格式为dd-mon-yyyy,我想将此日期与系统日期进行比较

[英]I have a date in(string) in dd-mon-yyyy format and I want to compare this date with system date

I have a date in(string) in dd-mon-yyyy format and I want to compare this date with system date. 我有一个日期格式为dd-mon-yyyy的(字符串),我想将此日期与系统日期进行比较。

eg. 例如。 I have 12-OCT-2010 and I want to compere this with system date in same format 我有2010年10月12日,我想用相同格式的系统日期来完成此操作

You can use the SystemDateFormat class to parse your String, for example 您可以使用SystemDateFormat类来解析您的String,例如

final DateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
final Date input = fmt.parse("12-OCT-2010");
if (input.before(new Date()) {
     // do something
}

Note that SimpleDateFormat is not threadsafe, so needs to be wrapped in a ThreadLocal if you have more than one thread accessing your code. 请注意, SimpleDateFormat不是线程安全的,因此如果您有多个线程来访问代码,则需要将它们包装在ThreadLocal

You may also be interested in Joda , which provides a better date API 您可能也对Joda感兴趣,它提供了更好的日期API

Use SimpleDateFormat http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html 使用SimpleDateFormat http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

    SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
    String d = "12-OCT-2010";
    try {
        Date formatted = f.parse(d);
        Date sysDate = new Date();
        System.out.println(formatted);
        System.out.println(sysDate);
        if(formatted.before(sysDate)){
            System.out.println("Formatted Date is older");
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I would recommend using Joda Time. 我建议使用Joda Time。 You can parse that String into a LocalDate object very simply, and then construct another LocalDate from the system clock. 您可以非常简单地将String解析为LocalDate对象,然后从系统时钟构造另一个LocalDate You can then compare these dates. 然后,您可以比较这些日期。

Using simpledateformat - 使用simpledateformat-

    String df = "dd-MMM-yyyy";
    SimpleDateFormat sdf = new SimpleDateFormat(df);
    Calendar cal = Calendar.getInstance();

    /* system date */
    String systemdate = sdf.format(cal.getTime());
    /* the date you want to compare in string format */
    String yourdate = "12-Oct-2010";
    Date ydate = null;
    try {
        ydate = sdf.parse(yourdate);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    yourdate = sdf.format(ydate);
    System.out.println(systemdate.equals(yourdate) ? "true" : "false");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM