Java simpledateformat returns 月份为零

Java simpledateformat returns zero for month

这可能是重复的,但我无法弄清楚为什么当指定为 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);
 }
}

输出为:

旧日期:8 月 26 日星期五 00:00:00 IST 2011
新日期:2011-00-26

当格式更改为 dd-mm-yyyy 且日期为 26-08-2011 时,输出为

旧日期:1 月 26 日,星期三 00:07:00 IST 2011
新日期:2011-07-26

我无法理解 MMM 失败的原因,我所有的日期都是格式 (26-Aug-2011),我需要将它们转换为 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.time

您正在使用麻烦的旧日期时间 类,现在已成为遗留问题,已被 java.time 类.

取代
String input = "26-Aug-2011" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f ) ;

您想要的 YYYY-MM-DD 输出格式恰好符​​合 ISO 8601 标准。 java.time 类 在 parsing/generating 字符串时默认使用标准格式。

String output = ld.toString() ;

2011-08-26

看到这个 code run live at IdeOne.com


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time 类.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

在哪里获取java.time类?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.