[英]I have a date in(string) in dd-mon-yyyy format and I want to compare this date with system date
我有一个日期格式为dd-mon-yyyy的(字符串),我想将此日期与系统日期进行比较。
例如。 我有2010年10月12日,我想用相同格式的系统日期来完成此操作
您可以使用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
}
请注意, SimpleDateFormat
不是线程安全的,因此如果您有多个线程来访问代码,则需要将它们包装在ThreadLocal
。
您可能也对Joda感兴趣,它提供了更好的日期API
使用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();
}
我建议使用Joda Time。 您可以非常简单地将String解析为LocalDate
对象,然后从系统时钟构造另一个LocalDate
。 然后,您可以比较这些日期。
使用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.