How do I create a DateFormat with an optional time argument?

回眸只為那壹抹淺笑 提交于 2019-12-14 00:52:24

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/4515023/how-do-i-create-a-dateformat-with-an-optional-time-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!