Java 包含第二个时SimpleDataFormat不进行解析
我得到了一个特定格式的时间,我想转换成另一种格式。下面的代码段取自其中一个堆栈溢出答案Java 包含第二个时SimpleDataFormat不进行解析,java,simpledateformat,Java,Simpledateformat,我得到了一个特定格式的时间,我想转换成另一种格式。下面的代码段取自其中一个堆栈溢出答案 SimpleDateFormat origDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm"); SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm"); Date retrivedDate = origDateFormat.parse(origFormat); r
SimpleDateFormat origDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date retrivedDate = origDateFormat.parse(origFormat);
return newDateFormat.format(retrivedDate);
只要我的输入日期为以下格式,此代码格式就有效:22/08/2015 14:23
。
但当我尝试使用秒时,我得到了错误:
不可上诉日期:“2019年3月6日14:17:25”
parse()
方法的javadoc,它是这样说的:
解析给定字符串开头的文本以生成日期。
该方法不能使用给定字符串的整个文本
因此,根据文档,您可以使用dd/MM/yyyy HH:MM
和dd/MM/yyyy HH:MM:ss
日期格式解析06/03/2019 14:17:25
日期。如果您使用不包含秒的格式进行解析,那么它将忽略第二部分。以下是工作代码:
String date = "06/03/2019 14:17:25";
SimpleDateFormat mmDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
SimpleDateFormat ssDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
System.out.println(mmDateFormat.parse(date));
System.out.println(ssDateFormat.parse(date));
以下是产出:
Wed Mar 06 14:17:00 GMT 2019
Wed Mar 06 14:17:25 GMT 2019
我可以使用上面发布的第二个代码片段解析
“06/03/2019 14:17:25”
。@MaruthiAdithya-不,SS是毫秒的格式。您可能想显示更多代码,因为您提供的代码工作正常。我正试图从csv文件解析此日期,所以此函数的输入是特定时间的字符串格式,代码的其他部分非常简单,我建议您不要使用SimpleDateFormat
和Date
。这些类设计得很糟糕,而且早已过时,其中前者尤其令人讨厌。而是使用来自的LocalDateTime
和DateTimeFormatter
。为什么要使用JDK 7文档?在解析时,将AM/PM附加到该日期是否会有所不同,示例:2019年3月6日2:17:35PM@Aarika对于12小时时间格式,您需要使用hh
而不是hh
。@uneq95这并不能证明错误是正确的,但这解释了错误可能是假警报以及不应该发生的原因。
Wed Mar 06 14:17:00 GMT 2019
Wed Mar 06 14:17:25 GMT 2019