简体   繁体   中英

null Date assigned by SimpleDateFormat.parse()

I hate to post another SimpleDateFormat question but I cannot find my answer on Google or in other threads. My code is below and the comments indicate the issue.

// The dateString format is "Thu Jul 19 00:04:11 +0000 2012". I confirmed that there
// is no preceding or trailing white space.
public static GregorianCalendar stringToDate(String dateString) {

    GregorianCalendar calendar = new GregorianCalendar();

    ParsePosition pos = new ParsePosition(0);

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d H:mm:ss Z yyyy");

    Date date = simpleDateFormat.parse(dateString, pos);


    // 'Unknown Source' error thrown by setTime() as date is ultimately null.
    calendar.setTime(date);

    return calendar;

}

I have confirmed my dateString parameter comes through correctly, my position object starts at 0 and I have reviewed the SimpleDateFormat numerous times against http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html . It looks right to me but I still tested various permutations of 'd' and 'H'. The only thing I can think is that there is some nuance to using this that I am missing, or I am way off base.

This compiles (javac 1.6.0_33), but when run (java version "1.6.0_33") it will not process even the first dateString value passed to it. I am running Windows 7 64-bit, Japanese version.

Any assistance is greatly appreciated.

If the current locale on your computer is Japanese (which is very likely the case here), then SimpleDateFormat will just take the default locale (Japanese) and try to parse the date with it.

If the date string is always in English, you should specify Locale.US in the SimpleDateFormat constructor .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM