首页 > 解决方案 > 如何将字符串时间戳读入形式为 Fri Jul 17 12:41:20 IST 2020 的 Java 日期?

问题描述

我有一个格式为 Fri Jul 17 12:41:20 IST 2020 的字符串,我想将其保存在列类型为 DATETIME 的 MS SQL 服务器表中。

为此,我首先需要将上述字符串转换为 Date POJO。

标签: java

解决方案


如果需要,您也可以存储 long ,但字符串到DateLong的基本转换。

 //Fri Jul 17 12:41:20 IST 2020
public static Long getDateTime(String input){
    SimpleDateFormat simpleDateFormat =  new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    try {
        Date date = simpleDateFormat.parse(input);
        return date.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    }
}

public static void main(String[] args){
    System.out.println(DateConverter.getDateTime("Fri Jul 17 12:41:20 IST 2020"));
}

推荐阅读