I wish to construct a date format that will optionally have a time argument.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd [hh:mm]");
Is it also possible to construct a date format object that is capable of parsing different formats? Such as try the current locale but then fall back to ISO-8601 or should I just write multiple date formats if one fails?
UPDATE: Looking back at this question I can see I didn't specify that the reason for multiple date formats was for parsing strings, not for formatting a date, thus ambiguity for formatting date objects wasn't a concern for me. If you take this into account the time portion is or is not included in the parsing string.
SimpleDateFormat won't let you do that. It doesn't support alternatives within a (single) format.
Even if it did, there would a problem. Consider using this
new SimpleDateFormat("yyyy-MM-dd [hh:mm]");
versus using
new SimpleDateFormat("yyyy-MM-dd hh:mm");
new SimpleDateFormat("yyyy-MM-dd ");
In the first case, when I parsed a date against the format, I couldn't tell the difference between "2010-01-01" and "2010-01-01 00:00" by looking at the Date
delivered to me. In the 2nd case, I can.
In the first case, when I format a Date with zero in the minutes and seconds fields, it is not clear whether the result should end with "00:00" ... or not. In the second case, this is entirely in the hands of the application.
I guess that what I'm really doing here is raising the issue that dates and date/times mean different things to different people and in different contexts. Sometimes they mean instants and sometimes intervals. Sometimes a lack of expressed precision means imprecision, and sometimes that the precision is implied.
As developers we have to run the line between writing software that is annoyingly picky, and software that makes incorrect assumptions about what the user actually means by a date / time value. The first step in getting it right for the user is understanding the complexity of the problem. Overloading variations into a single format string is (would be) sweeping the problem under the carpet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With