How to convert String time stamp to java.sql.Times

2019-02-21 09:07发布

问题:

I have time stamp in String format as "Thu, 23 Feb 2017 04:56:38 GMT". So, how can convert this string time stamp into "2017-02-23 04:56:38.0" format. I tried link java converting date in string format to timestamp . But facing error in conversion. My sample code is as below.

String str = "Thu, 23 Feb 2017 04:56:38 GMT";


    SimpleDateFormat sdf1 = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss a");
    Date date = null;
    try {
        date = (Date) sdf1.parse(str);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Date Object:" + date);
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println("Formatted Date:" + sdf2.format(date));

Error: java.text.ParseException: Unparseable date: "Thu, 23 Feb 2017 04:56:38 GMT" at java.text.DateFormat.parse(DateFormat.java:366)

回答1:

Just change the sdf1 format

SimpleDateFormat sdf1 = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z");

Here z means

Date or Time Component  Presentation        Examples
Time zone               General time zone   Pacific Standard Time; PST; GMT-08:00


回答2:

I am aware that you have got it to work now. Please allow me to mention anyway: Your format is built-in as java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME. So parsing your string is a one-liner:

    Instant i = OffsetDateTime.parse(str, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant();

Since you were asking for a java.sql.Timestamp in your title, I was thinking that you might need this for your database? A modern JDBC driver (version 4.2 or newer) should be able to accept an Instance directly. If you are not that lucky, it’s still easy:

    Timestamp ts = Timestamp.from(i);

I am using some of the classes in the java.time package (with subpackage java.time.format). The above is just a very simple example of where these are more programmer-friendly than the old classes Timestamp and SimpleDateFormat (from Java 1.0 or 1.1, I think). I keep meeting examples every time I use them (and certainly when I answer quetions on Stack Overflow about tricky bugs in using the old classes).

java.time is standard in Java 8. If you want to use the classes in Java 6 or 7, get them in the ThreeTen Backport.