Java 将字符串转换为“yyyy-MM-dd HH:mm:ss”时出现无法解析的日期异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21826548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:54:41  来源:igfitidea点击:

Unparseable date exception when converting a string to "yyyy-MM-dd HH:mm:ss"

javasqlparsingdatetimesybase

提问by Achilles

Hi I am trying to convert a string 19611015 to a date formate of ("yyyy-MM-dd HH:mm:ss") before storing it into a sybase database table. I have tried the below code which gives me the error:

嗨,我正在尝试将字符串 19611015 转换为 ("yyyy-MM-dd HH:mm:ss") 的日期格式,然后再将其存储到 sybase 数据库表中。我试过下面的代码,这给了我错误:

Unparseable date: "19611015"

无法解析的日期:“19611015”

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(formatter.parse("19611015"));

I have been reading some long and complex solutions to this, some suggesting to use Locale. Could someone explain maybe an alternative simple solution to convert string I have to a date format I am after above. Thank you.

我一直在阅读一些长而复杂的解决方案,有些建议使用 Locale。有人可以解释一下,将字符串转换为我所追求的日期格式的另一种简单解决方案。谢谢你。

采纳答案by Kick

The datein string is in yyyyMMdd format and want to convert it into yyyy-MM-dd HH:mm:ss so use below code :

date字符串是YYYYMMDD格式,并希望将其转换成YYYY-MM-DD HH:MM:SS所以下面的代码使用:

        DateFormat originalFormat = new SimpleDateFormat("yyyyMMdd");
        DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = originalFormat.parse("19611015");
        String formattedDate = targetFormat.format(date); 
        System.out.println(formattedDate);

Output :

输出 :

1961-10-15 00:00:00

回答by Nikhil Joshi

Achilles, below code might solve your problem:

阿基里斯,下面的代码可能会解决您的问题:

package com.test;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class LongToDate {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(19611015 * 1000);
        String dateFormatString = "yyyy-MM-dd HH:mm:ss";
        DateFormat dateFormat = new SimpleDateFormat(dateFormatString);
        String result = dateFormat.format(cal.getTime());
        System.out.println(result);
        //Output: 1969-12-10 15:46:18
    }
}