简体   繁体   中英

Can't parse string to date

Server return me date in format "Sat, 10 Jan 2015 07:24:00 +0100".

I try to parse this string to date, but it was unsuccessful.

This my code of parsing:

    SimpleDateFormat format = new SimpleDateFormat("dd.Mm.yyyy");
        try {
            Date date = format.parse("Sat, 10 Jan 2015 07:24:00 +0100");
            tvDate.setText(date.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }

This is the format that you want to use:

SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");

Why?

The documentation goes over the symbols , but for the most part...

  • EEE matches a shorthand day
  • dd matches a two-digit date (so 01 through 31)
  • MMM matches a three-letter month (so Jan)
  • yyyy matches a four-letter year
  • HH:mm:ss Z is shorthand (enough) for the full 24-hour clock with Z representing the offset from GMT.

You should use a format like this if you don't care about the +0100:

SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss");

E - is day of week like "Sat"

d - day of month

M - is month

y - is year

h - is hour

m - is minute

s - is second

If you really care about the timezone, what you need to do is changing the String format of your SimpleDateFormat instance into something that represents the date String that is being returned.

Here is an example:

public static Date stringToDate(String dateString) throws ParseException {
    final SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    return format.parse(dateString);

}

public static void main(final String[] args) throws ParseException {
    Date example = stringToDate(
            "Sat, 10 Jan 2015 07:24:00 +0100");
}

You might also want to consider that SimpleDateFormat is not thread-safe and could cause unexpected behavior if not used properly. Here is a very useful explanation about this:

http://javarevisited.blogspot.com/2012/03/simpledateformat-in-java-is-not-thread.html

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