本文介绍了Java:将字符串转换为TimeStamp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试将String转换为TimeStamp时,我有一个问题。我有一个数组,日期格式为 yyyy-MM-dd
,我想以 yyyy-MM-dd的格式更改HH:mm:ss.SSS
。所以,我使用这个代码:
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);
日期d = formatter.parse(oldDateString);
((SimpleDateFormat)formatter).applyPattern(NEW_FORMAT);
newDateString = formatter.format(d);
System.out.println(newDateString);
时间戳ts = Timestamp.valueOf(newDateString);
System.out.println(ts);
,我得到以下结果。
但是当我尝试简单地做
String text = 2011-10-02 18:48:05.123;
ts = Timestamp.valueOf(text);
System.out.println(ts);
我得到正确的结果:
你知道我可能做错了吗?
感谢您的帮助。
解决方案
请按照以下步骤获取正确的结果:
try {
pre>
SimpleDateFormat dateFormat = new SimpleDateFormat(yyyy-MM-dd hh:mm:ss.SSS);
日期parsedDate = dateFormat.parse(yourString);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
} catch(Exception e){//这个泛型,但你可以控制另一种类型的异常
看起来的排除的起源
}
请注意,
.parse(String)
可能会抛出一个ParseException
。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 ofyyyy-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);
and I get the following result.
but when I try to simply do
String text = "2011-10-02 18:48:05.123"; ts = Timestamp.valueOf(text); System.out.println(ts);
I get the right result:
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 }
Please note that
.parse(String)
might throw aParseException
.这篇关于Java:将字符串转换为TimeStamp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!