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.
eg. I have 12-OCT-20开发者_开发百科10 and I want to compere this with system date in same format
You can use the SystemDateFormat
class to parse your String, for example
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.
You may also be interested in Joda, which provides a better date API
Use 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. 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.
Using 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");
精彩评论