Storing a date in .property and comparing with current date
How do I store a future date in 开发者_如何学编程a .property file and compare this date with current the current date?
You could:
- save a formatted date
- if you want, save the format too, adding flexibility
The property file:
myDate=25/01/2012
myDate.pattern=dd/MM/yyyy
Then, in your program you could load the date this way:
// choose one of two lines!
String pattern = "dd/MM/yyyy"; // for a fixed format
String pattern = propertyFile.getProperty("myDate.pattern");
String formattedDate = propertyFile.getProperty("myDate");
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date myDate = format.parse(formattedDate);
Edit: to compare to current...
1. boolean isFuture = myDate.after(new Date())
2. boolean isPast = myDate.before(new Date())
3. int compare = myDate.compareTo(new Date());
// compare < 0 => before
// compare == 0 => equal
// compare > 0 => after
Well, there are a few things to consider here:
- Do you genuinely only care about the date, or is it the date and time?
- Does the time zone matter? Are you interested in a future instant, or a future local time?
- Should the properties file be human readable?
If you're just dealing with an instant and you don't care about anyone being able to understand which instant it is from the properties file, I'd be tempted to store the string representation of a long
(i.e. the millis in a java.util.Date
) and then to check it, just parse the string and compare the result with System.currentTimeMillis
. It avoids the whole messy formatting and parsing of dates and times.
For anything more complicated, I'd thoroughly recommend using Joda Time which will make it easier to understand what concepts you're really dealing with (e.g. LocalDate
, LocalTime
or DateTime
) and which has better formatting and parsing support (IMO) than the JDK.
精彩评论