Java SimpleDataFormat类中的月份问题
然而,当它返回时,它给出了2016年1月14日 所需输出为2016年3月14日Java SimpleDataFormat类中的月份问题,java,android,datetime,simpledateformat,Java,Android,Datetime,Simpledateformat,然而,当它返回时,它给出了2016年1月14日 所需输出为2016年3月14日 String expiryDate = "2016-03-14"; private String formatDateTime(String expiryDate, String expiryTime) { SimpleDateFormat input = new SimpleDateFormat("yyyy-mm-dd"); SimpleDateFormat output = new SimpleD
String expiryDate = "2016-03-14";
private String formatDateTime(String expiryDate, String expiryTime) {
SimpleDateFormat input = new SimpleDateFormat("yyyy-mm-dd");
SimpleDateFormat output = new SimpleDateFormat("MMM, dd, yyyy");
try {
String formattedDate = output.format(input.parse(expiryDate ));// parse input
return formattedDate + ", " + expiryTime;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
应该是
SimpleDateFormat input = new SimpleDateFormat("yyyy-mm-dd");
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd");
mm应该是mmmm表示分钟,因此当您使用mm时,它将打印分钟而不是月份 而MM代表月份。您需要添加如下内容:
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd");
mm
应为大写mm
。因为
mm表示分钟
MM表示月份
所以你的格式应该是
需要对上述声明进行如下更正:
SimpleDateFormat input = new SimpleDateFormat("yyyy-mm-dd");
使用MM代替MM,因为MM用于月份,而MM用于分钟。
java.text.simpleDataFormat
内部调用java.util.Locale
,实际实现了日期时间和区域格式模式。因此,在Locale
MM中定义月份,而MM定义分钟。所以,使用
SimpleDataFormat输入=新的SimpleDataFormat(“yyyy-mm-dd”)代码>将不匹配任何模式,因此默认情况下,月份将设置为其默认值1
。它显示为Jan
,而不是Mar
(这是您实际期望的)
使用MM表示月份。它会解决你的问题
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd");
你的问题已经回答了,其他答案都是正确的。我想提供你的方法的现代版本
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd");
当我用2016-03-14
的expiryDate
调用此方法时,我得到了2016年3月14日的
java.time
您使用的SimpleDateFormat
(以及其他答案也使用的)不仅早已过时,而且是出了名的麻烦。我建议您忘记它,而是使用现代java日期和时间APIjava.time
。和你一起工作真是太好了
您的输入格式,2016-03-14
,符合ISO 8601,现代类默认解析的格式,即没有任何显式格式化程序。因此,在格式模式字符串中甚至不可能出现MM
错误的情况
链接:解释如何使用java。时间mm
应该是大写的mm
你想要什么格式???@MD感谢你的解决方案奏效。你能发布一个答案吗?只要SimpleDateFormat
没有达到你期望的效果,你就会接受,始终检查文档并仔细检查格式模式。@FarazDurrani是的,对
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd");
private static DateTimeFormatter output
= DateTimeFormatter.ofPattern("MMM, dd, yyyy", Locale.ENGLISH);
private static String formatDateTime(String expiryDate, String expiryTime) {
String formattedDate = LocalDate.parse(expiryDate).format(output);
return formattedDate + ", " + expiryTime;
}