如何在Java中将日期字符串转换为正确的格式? [英] How to convert a date String into the right format in Java?
问题描述
2009-10-27 14:36:59.580250
into
27.10.2009,14:36 ?
第一个日期可以作为字符串使用,第二个日期也可以是一个字符串;)到目前为止,我不是在Java中进行日期转换...
提前感谢
您可以使用 java.text.SimpleDateFormat
for这个。第一步是使用 SimpleDateFormat
将第一个字符串解析成 java.util.Date
对象,第一个字符串下一步是根据第二个字符串的模式将获取的 java.util.Date
对象格式化成一个字符串。例如:
String datestring1 =2009-10-27 14:36:59.580250;
Date date1 = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss)。parse(datestring1);
String datestring2 = new SimpleDateFormat(dd.MM.yyyy HH:mm)。format(date1);
System.out.println(datestring2);
修改:我已经删除了。 SSSSSS
部分从第一个模式,因为它失败。但是在我看来,它应该在理论上与yyyy-MM-dd HH:mm:ss.SSS
和yyyy-MM- dd HH:mm:ss.SSSSSS
,但它是计算它们为秒!我认为这是在 SimpleDateFormat
中的错误实现。 JodaTime 可以完美地处理这些模式的微数据。
Can somebody please explain to me how I can convert
2009-10-27 14:36:59.580250
into
27.10.2009, 14:36 ?
The first date is available as a string and the second one should be a string as well ;) Up to now I'm not so into date conversion within Java...
Thanks in advance!
You can use java.text.SimpleDateFormat
for this. First step is to parse the first string into a java.util.Date
object using SimpleDateFormat
based on the pattern of the first string. Next step is to format the obtained java.util.Date
object into a string based on the pattern of the second string. For example:
String datestring1 = "2009-10-27 14:36:59.580250";
Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(datestring1);
String datestring2 = new SimpleDateFormat("dd.MM.yyyy HH:mm").format(date1);
System.out.println(datestring2);
Edit: I've removed the .SSSSSS
part from the first pattern because it failed. But in my opinion it should in theory have worked with "yyyy-MM-dd HH:mm:ss.SSS"
and "yyyy-MM-dd HH:mm:ss.SSSSSS"
as well, but it is calculating them as seconds! I consider this as a buggy implementation in SimpleDateFormat
. The JodaTime handles the millis/micros perfectly with those patterns.
这篇关于如何在Java中将日期字符串转换为正确的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!