![](/img/trans.png)
[英]SimpleDateFormat not parsing milliseconds and MySql is rounding Date
[英]Parsing String to Date with SimpleDateFormat, nb of milliseconds varying
我在文本文件的字符串中有這樣一個日期: String string = 2014-10-03 00:58:59.765
所以我用這種方式解析:
Date timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.parse(string);
但是,某些時間戳的毫秒數少於3位,並且我收到一個ParseException,試圖在它們上使用相同的SimpleDateFormat。 編輯:毫秒為000時發生。示例: java.text.ParseException: Unparseable date: "2014-10-03 00:59:49"
這是我的工作:
if (string.length() == 23) {
timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.parse(string);
} else if (string.length() == 22) {
timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS")
.parse(string);
} else if string.length() == 21) {
timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS")
.parse(string);
} else if (string.length() == 19) {
timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse(string);
}
難道沒有更好的方法嗎?
您可以借助來決定.
在包含SSS
String中,並注意它並不總是安全的,因此要小心,因為SSS
可以解析.767
, .76
, .7
毫秒 。
Date timestamp = null;
if(string.contains(".")) {
timestamp =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.parse(string);
} else {
timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse(string);
}
System.out.println(timestamp);
請注意,如果您使用.SSS
解析毫秒 .76
, .SSS
不是在檢索期間必須使用.SS
對其進行格式化,否則它將返回.076
而不是.76
,其他情況.076
發生。 所以,要小心!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.