Java:将字符串转换为时间戳 [英] Java: Convert String to TimeStamp
本文介绍了Java:将字符串转换为时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在尝试将字符串转换为时间戳时遇到问题.我有一个数组,其日期格式为 yyyy-MM-dd
,我想更改为 yyyy-MM-dd HH:mm:ss.SSS格式代码>.所以,我使用这个代码:
I have an issue while I try to convert a String to a TimeStamp. I have an array that has the date in the format of yyyy-MM-dd
and I want to change in the format of yyyy-MM-dd HH:mm:ss.SSS
. So, I use this code:
final String OLD_FORMAT = "yyyy-MM-dd";
final String NEW_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
String oldDateString = createdArray[k];
String newDateString;
DateFormat formatter = new SimpleDateFormat(OLD_FORMAT);
Date d = formatter.parse(oldDateString);
((SimpleDateFormat) formatter).applyPattern(NEW_FORMAT);
newDateString = formatter.format(d);
System.out.println(newDateString);
Timestamp ts = Timestamp.valueOf(newDateString);
System.out.println(ts);
我得到以下结果.
2009-10-20 00:00:00.000
2009-10-20 00:00:00.000
2009-10-20 00:00:00.0
2009-10-20 00:00:00.0
但是当我尝试简单地做
String text = "2011-10-02 18:48:05.123";
ts = Timestamp.valueOf(text);
System.out.println(ts);
我得到了正确的结果:
2011-10-02 18:48:05.123
2011-10-02 18:48:05.123
你知道我做错了什么吗?感谢您的帮助.
Do u know what I might be doing wrong? Thanks for the help.
推荐答案
按照以下步骤获得正确的结果:
Follow these steps for a correct result:
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date parsedDate = dateFormat.parse(yourString);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch(Exception e) { //this generic but you can control another types of exception
// look the origin of excption
}
请注意.parse(String)
可能会抛出 ParseException
.
这篇关于Java:将字符串转换为时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文