开发者

Java String to Date, ParseException

I have a stri开发者_如何学运维ng named DateCompareOld, it has the value "Fri Aug 12 16:08:41 EDT 2011". I want to convert this to a date object.

 SimpleDateFormat dateType =  new SimpleDateFormat("E M dd H:m:s z yyyy");
 Date convertDate = dateType.parse(DateCompareOld);

But everytime I try this, I get a parse exception. I have tried other SimpleDateFormat formatting criteria, but it always fails.

Suggestions?


Try this format:

EEE MMM dd HH:mm:ss zzz yyyy

Quick test:

public static void main(String[] args) throws Exception {
    DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
    System.out.println(df.parse("Fri Aug 12 16:08:41 EDT 2011"));
}

// outputs
Fri Aug 12 15:08:41 CDT 2011

Output is in CDT, since that's where I am, but the value is right.


DateFormat dateType =  new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
dateType.setLenient(false);
Date convertDate = dateType.parse(DateCompareOld);


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*.

Another important thing to note is that your string has English text and therefore you must use Locale.ENGLISH so that you do not get an exception or some wrong result when your code is run on a JVM whose Locale is not English. Anyway, NEVER use a date-time parsing/formatting type (e.g. SimpleDateFormat, DateTimeFormatter etc.) without Locale because these types are Locale-sensitive.

Demo using modern date-time API:

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

public class Main {
    public static void main(String args[]) {
        String strDateTime = "Fri Aug 12 16:08:41 EDT 2011";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("E MMM d H:m:s z u", Locale.ENGLISH);
        ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
        System.out.println(zdt);
    }
}

Output:

2011-08-12T16:08:41-04:00[America/New_York]

If at all, you need a java.util.Date object, you can obtain it as follows:

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

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

Using the legacy API:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String args[]) throws ParseException {
        String strDateTime = "Fri Aug 12 16:08:41 EDT 2011";
        SimpleDateFormat sdf = new SimpleDateFormat("E MMM d H:m:s z y", Locale.ENGLISH);
        Date date = sdf.parse(strDateTime);
        // ...
    }
}

Note that the java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). When you print an object of java.util.Date, its toString method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat and obtain the formatted string from it.


* 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.


Note the String passed to SimpleDateFormat() should be corrected to "EEE MMM dd HH:mm:ss z yyyy"

Here is the code:

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class DateTest{
public static void main(String []args){
    String DateCompareOld = "Fri Aug 12 16:08:41 EDT 2011";
    SimpleDateFormat dateType =  new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    Date convertDate = new Date();
    try{
     convertDate = dateType.parse(DateCompareOld);
    }catch(ParseException pex){
        pex.printStackTrace();
    }
    System.out.println(convertDate.toString());
  }

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜