Java 我在(字符串)中有一个 dd-mon-yyyy 格式的日期,我想将此日期与系统日期进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3912610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
I have a date in(string) in dd-mon-yyyy format and I want to compare this date with system date
提问by Sanjeev
I have a date in(string) in dd-mon-yyyy format and I want to compare this date with system date.
我有一个 dd-mon-yyyy 格式的日期 in(string),我想将此日期与系统日期进行比较。
eg. I have 12-OCT-2010 and I want to compere this with system date in same format
例如。我有 12-OCT-2010,我想以相同的格式将其与系统日期进行比较
采纳答案by Jon Freedman
You can use the SystemDateFormat
class to parse your String, for example
例如,您可以使用SystemDateFormat
该类来解析您的字符串
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
如果您有多个线程访问您的代码,则需要将其包装在 a 中。
You may also be interested in Joda, which provides a better date API
您可能还对Joda感兴趣,它提供了更好的日期 API
回答by dty
I would recommend using Joda Time. You can parse that String into a LocalDate
object very simply, and then construct another LocalDate
from the system clock. You can then compare these dates.
我建议使用 Joda Time。您可以LocalDate
非常简单地将该字符串解析为一个对象,然后LocalDate
根据系统时钟构造另一个对象。然后您可以比较这些日期。
回答by Kevin D
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();
}
回答by Johnbabu Koppolu
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");