Pergunta

am getting date as string

String dateStr = Mon Mar 31 2014 00:00:00 GMT+0530 (India Standard Time) 

but am getting unparsable date exception when am tring to parse using SimpleDateFormat

java.util.Date date = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z", Locale.ENGLISH).parse(dateStr);

please help me to solve this

Foi útil?

Solução

The "GMT" part is confusing things - the Z format specifier expects just "0800" or similar.

You can change your format to:

"EEE MMM dd yyyy HH:mm:ss 'GMT'Z"

and that will work. (It's ignoring the time zone name at the end of the string, of course.)

Outras dicas

This'll work:

java.util.Date date = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", Locale.ENGLISH).parse(dateStr);

java.time

The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API*.

Demo using modern date-time API:

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.util.Locale;

public class Main {
    public static void main(String args[]) {
        String dateStr = "Mon Mar 31 2014 00:00:00 GMT+0530 (India Standard Time)";
        
        DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                .parseCaseInsensitive()
                                .appendPattern("EEE MMM d u H:m:s")
                                .appendLiteral(' ')
                                .appendZoneId()
                                .appendPattern("X")
                                .appendLiteral(" (")
                                .appendZoneText(TextStyle.FULL)
                                .appendLiteral(')')
                                .toFormatter(Locale.ENGLISH);
        
        ZonedDateTime zdt = ZonedDateTime.parse(dateStr, dtf);
        
        System.out.println(zdt);
    }
}

Output:

2014-03-31T00:00+05:30[Asia/Kolkata]

For any reason, if you need an object of java.util.Date from this object of ZonedDateTime, you can so as follows:

Date date = Date.from(zdt.toInstant());

Learn more about the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top