[英]Unparseable date exception when converting a string to “yyyy-MM-dd HH:mm:ss”
嗨我想将字符串19611015转换为日期格式(“yyyy-MM-dd HH:mm:ss”),然后将其存储到sybase数据库表中。 我尝试了下面的代码,它给了我错误:
无法解释的日期:“19611015”
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(formatter.parse("19611015"));
我一直在阅读一些长而复杂的解决方案,有些人建议使用Locale。 有人可能会解释一个替代的简单解决方案,将字符串转换为我之前的日期格式。 谢谢。
字符串中的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);
输出:
1961-10-15 00:00:00
Achilles,代码下面可能会解决您的问题:
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.