这可能是重复的,但我无法弄清楚为什么当指定为 MMM 时月份返回为零并且与 mm(numeric) 配合良好。如有任何帮助,我们将不胜感激?
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Locale;
public class time1 {
public static void main(String[] args) {
DateFormat originalFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyy-mm-dd");
Date date = null;
try {
date = originalFormat.parse("26-Aug-2011");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String formattedDate = targetFormat.format(date);
System.out.println("old date: " + date);
System.out.println("new date: " + formattedDate);
}
}
输出为:
旧日期:2011 年 8 月 26 日星期五 00:00:00 IST
新日期:2011-00-26
当格式更改为 dd-mm-yyyy 且日期为 26-08-2011 时,输出为
旧日期:2011 年 1 月 26 日星期三 00:07:00 IST
新日期:2011-07-26
我无法理解 MMM 失败的原因,我所有的日期都是格式(2011 年 8 月 26 日),我需要将它们转换为 yyyy-mm-dd (26-07-2011) .
最佳答案
来自documentation ,我可以这么说
DateFormat targetFormat = new SimpleDateFormat("yyyy-mm-dd");
需要改为
DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
// this gives you the Date in Digits.
根据文档,
'M' is used for Month in Year, whereas
'm' is used for Minute in Hour.
因此,您的“mm”将返回默认为 00:00 的分钟数,这是您得到的输出。这将为您提供以下输出。
old date: Fri Aug 26 00:00:00 IST 2011
new date: 2011-08-26
关于Java simpledateformat 返回零表示月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46357295/