Java - Date构造函数接受Date String,但不推荐使用。试过替代品,但没有运气 [英] Java - Date constructor accepts a Date String, But deprecated. Tried alternatives, but no luck
问题描述
String temp_date="07/28/2011 11:06:37 AM";
Date date = new Date(temp_date); //Depricated
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss");
String comp_date= sdf.format(date);
System.out.println(comp_date);
这有效,但是如果我使用这样的东西,那么
This works, But If I use something like this
String temp_date="07/28/2011 11:06:37 AM";
try{
SimpleDateFormat sdf = new SimpleDateFormat("MMM-dd-yyyy hh:mm:ss");
Date comp_date= sdf.parse(temp_date);
System.out.println(comp_date);
}catch(Exception e){
System.out.println(e);
}
抛出此异常:
java.text.ParseException: Unparseable date: "07/28/2011 11:06:37 AM"
推荐答案
您的解析模式是错误的。它与日期字符串表示不匹配。 MMM
表示3个字母的本地化月份缩写,而实际日期中您有两位数的月份号,您需要 MM
。您还将 /
作为日期/月/年分隔符而不是 -
。对于AM / PM标记,您还需要一个 a
,以便可以解析正确的 hh
。
Your parsing pattern is wrong. It does not match the date string representation. The MMM
denotes a 3-letter localized month abbreviation, while you have 2-digit month number in your actual date, you need MM
. You've also slashes /
as date/month/year separator and not -
. For the AM/PM marker you also need an a
afterwards so that the right hh
can be parsed.
这应该工作:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
有关这些模式的说明,请阅读 SimpleDateFormat
javadoc 。
For an explanation of those patterns, read the SimpleDateFormat
javadoc.
我相信您具体的功能要求是转换由 MM / dd / yyyy hh:mm:ss a
转换为另一个日期字符串格式,由模式 MMM-dd-yyyy hh:mm:ss
指定。在这种情况下,您应该有两个 SimpleDateFormat
实例,一个将给定模式中的字符串解析为 Date
另一个将解析的 Date
格式化为给定模式。这应该做你想要的:
I believe that your concrete functional requirement is to convert the given date string as specified by the pattern MM/dd/yyyy hh:mm:ss a
into another date string format, as specified by the pattern MMM-dd-yyyy hh:mm:ss
. In that case, you should then have two SimpleDateFormat
instances, one which parses the string in the given pattern to a Date
and another which formats the parsed Date
to the given pattern. This should do what you want:
String inputDate = "07/28/2011 11:06:37 AM";
Date date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a").parse(inputDate);
String outputDate = new SimpleDateFormat("MMM-dd-yyyy HH:mm:ss").format(date);
System.out.println(outputDate); // Jul-28-2011 11:06:37
请注意,我更改了 hh
的输出为 HH
,因为否则最终会在1-12小时的表示中没有 AM / PM标记。 HH
表示为0-23小时。
Note that I changed hh
in output to be HH
because it would otherwise end up in 1-12 hour representation without an AM/PM marker. The HH
represents it as 0-23 hour.
这篇关于Java - Date构造函数接受Date String,但不推荐使用。试过替代品,但没有运气的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!