java SimpleDateFormat 的毫秒问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16136860/
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-10-31 22:01:09  来源:igfitidea点击:

Issue with SimpleDateFormat's milliseconds

javadatedatetimesimpledateformatmilliseconds

提问by Pith

I tried this snippet code and the output is very surprising. Why the output is different from the input? Did I make a mistake or is there a problem with SimpleDateFormat?

我尝试了这个片段代码,输出非常令人惊讶。为什么输出与输入不同?是我弄错了还是 SimpleDateFormat 有问题?

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS");
try {
    Date date = sdf.parse("2013-04-18-19.01.33.080");
    System.out.println(sdf.format(date)); // output: 2012-04-18-19.01.33.80
} catch (ParseException e) {
    e.printStackTrace();
}

EDIT:In fact, I checked my code and I wrote yyyy-MM-dd-HH.mm.ss.Sinstead of yyyy-MM-dd-HH.mm.ss.SSS. It was a stupid mistake. Thanks all for your answers.

编辑:事实上,我检查了我的代码,我写的yyyy-MM-dd-HH.mm.ss.S不是yyyy-MM-dd-HH.mm.ss.SSS. 这是一个愚蠢的错误。谢谢大家的回答。

采纳答案by Jigar Joshi

This works fine for me, If it doesn't work for you try setting Localeexplicitly

这对我来说很好,如果它对你不起作用,请尝试Locale明确设置

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS", Locale.ENGLISH);