开发者

Regarding format date/time in java

I have two datetime formats,

  1. 'dd-mm-yyyy' and
  2. 'dd-mm-yyyy hh:MM:ss'

in my application. The input value may be a string in any of above forms.

I want to store this date value in database. So, first I format it with SimpleDateFormatter. But how can I check that input string is of type 1 or of type 2?

If input date time type is in form of (2) and I format datetime with formatter 'dd-mm-yyyy' then it returns null.

Whatever input type - it must be converted according to inp开发者_Python百科ut. In short, how can I check input datetime format?


i want to store this date value in data base. So, first i formate it with SimpleDateFormatter , but how can i check that input string is type of 1 or type of 2.

It sounds like you want to parse the value - you shouldn't be storing it in the database as a string. (Parsing is converting from a string to the natural data type, e.g. Date. Formatting is converting from a value to a string.)

You can just try parsing the value using DateFormat.parse, and catching the exception thrown if the text is invalid - but you should be aware that your format strings are wrong. 'M' is for month-of-year, and 'm' is for minutes, not the other way round. You also probably want the 24 hour clock (H), not the 12 hour clock (h), so you want:

dd-MM-yyyy

dd-MM-yyyy HH:mm:ss

Finally, I'd strongly advise you to use Joda Time instead of the built-in date/time classes. Joda Time is a much better API. (For example, the formatters in Joda Time are thread-safe, unlike those in the JRE...)


Firstly, your data format is screwed up - you have minutes (mm) and months (MM) around the wrong way. ie your formats should be:

"dd-MM-yyyy"
"dd-MM-yyyy HH:mm:ss"

Next, rather than being too smart about it, you can simply try each format and see what works:

public static Date parseDate(String input) {
    String[] formats = { "dd-MM-yyyy", "dd-MM-yyyy HH:mm:ss" }; // Add more as you like

    for (String format : formats) {
        try {
            return new SimpleDateFormat(format).parse(input);
        }
        catch (ParseException e) {
            // Ignore and continue
        }
    }
    throw new IllegalArgumentException("Could not parse date from " + input);
}


There are many possibilities to distinguish the two formats. An easy one is to check the length of the input string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜