如何将String时间戳转换为java.sql.Timestamp? [英] How to convert String time stamp to java.sql.Timestamp?

查看:1364
本文介绍了如何将String时间戳转换为java.sql.Timestamp?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的时间戳为String格式为星期四,2017年2月23日04:56:38 GMT。那么,如何将此字符串时间戳转换为2017-02-23 04:56:38.0格式。
我尝试将 java转换为字符串格式的日期链接到时间戳。但面临转换错误。
我的示例代码如下。

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));

错误:java.text.ParseException:无法解释日期:星期四,2017年2月23日04:56: 38 GMT
at java.text.DateFormat.parse(DateFormat.java:366)

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

推荐答案

只需更改sdf1格式

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

此处 z 表示

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

这篇关于如何将String时间戳转换为java.sql.Timestamp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆