Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Date Parsing "a.m." and "p.m."

Using SimpleDateFormat, how can you parse the String: "2013-05-23T09:18:07 p.m..380+0000"

All my SimpleDateFormat Strings are tripping up on the "p.m." part.

Thanks in advance.

EDIT: We have no control over the format coming in.

I've tried:

"yyyy-MM-dd'T'HH:mm:ss a.a..SSSZ"

"yyyy-MM-dd'T'HH:mm:ss aaaa.SSSZ"

"yyyy-MM-dd'T'HH:mm:ss a.'m'..SSSZ"

"yyyy-MM-dd'T'HH:mm:ss a.'m.'.SSSZ"

"yyyy-MM-dd'T'HH:mm:ss a.'m..'SSSZ"

"yyyy-MM-dd'T'HH:mm:ss aa'm'..SSSZ"

"yyyy-MM-dd'T'HH:mm:ss aa'm.'.SSSZ"

"yyyy-MM-dd'T'HH:mm:ss aaa'..'SSSZ"

"yyyy-MM-dd'T'HH:mm:ss aaa.'.'SSSZ"

"yyyy-MM-dd'T'HH:mm:ss aaa'.'.SSSZ"
like image 540
mtical Avatar asked Dec 06 '22 07:12

mtical


1 Answers

It's not clear what the "380+0000" part is meant to be, but you can fix the AM/PM part, by setting the DateFormatSymbols for the SimpleDateFormat. Here's an example:

import java.util.*;
import java.text.*;

public class Test {
    public static void main(String[] args) throws Exception {
        String text = "2013-05-23T09:18:07 p.m..380+0000";
        String pattern = "yyyy-MM-dd'T'hh:mm:ss aa'.380+0000'";

        SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("UTC"));

        DateFormatSymbols symbols = format.getDateFormatSymbols();
        symbols = (DateFormatSymbols) symbols.clone();
        symbols.setAmPmStrings(new String[] { "a.m.", "p.m."});
        format.setDateFormatSymbols(symbols);

        Date date = format.parse(text);
        System.out.println(date);
    }
}  

I don't know whether you have to clone the DateFormatSymbols before mutating it - it's not clear, to be honest... the documentation points two ways:

DateFormatSymbols objects are cloneable. When you obtain a DateFormatSymbols object, feel free to modify the date-time formatting data. For instance, you can replace the localized date-time format pattern characters with the ones that you feel easy to remember. Or you can change the representative cities to your favorite ones.

Given that it's mentioning cloning, that suggests you should clone - but then the subsequent paragraph suggests not :(

like image 159
Jon Skeet Avatar answered Dec 15 '22 00:12

Jon Skeet