简体   繁体   中英

Java date format conversion - getting wrong month

I have a problem in converting the date in java, don't know where i am going wrong...

    String dateStr = "2011-12-15";
    String fromFormat = "yyyy-mm-dd";
    String toFormat = "dd MMMM yyyy";

    try {
        DateFormat fromFormatter = new SimpleDateFormat(fromFormat);
        Date date = (Date) fromFormatter.parse(dateStr);

        DateFormat toformatter = new SimpleDateFormat(toFormat);
        String result = toformatter.format(date);

    } catch (ParseException e) {
        e.printStackTrace();
    }

Input date is 2011-12-15 and I am expecting the result as "15 December 2011", but I get it as "15 January 2011"

where am I going wrong?

您的fromFormat使用分钟,而它应该使用几个月。

String fromFormat = "yyyy-MM-dd";

I think the fromFormat should be "yyyy-MM-dd".

Here is the format:

  • m == Minute in Hour
  • M == Month in Year

More: http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Look at the javadoc of SimpleDateFormat and look at what the m represents. Not months as you think but minutes.

 String fromFormat = "yyyy-MM-dd"; 

从格式应该是:

String fromFormat = "yyyy-MM-dd"

tl;dr

LocalDate.parse( "2011-12-15" )                            // Date-only, without time-of-day, without time zone.
.format(                                                   // Generate `String` representing value of this `LocalDate`. 
    DateTimeFormatter.ofLocalizedDate( FormatStyle.LONG )  // How long or abbreviated?
                     .withLocale(                          // Locale used in localizing the string being generated.
                         new Locale( "en" , "IN" )         // English language, India cultural norms.
                     )                                     // Returns a `DateTimeFormatter` object.
)                                                          // Returns a `String` object.

15 December 2011

java.time

While the accepted Answer is correct (uppercase MM for month), there is now a better approach. The troublesome old date-time classes are now legacy, supplanted by the java.time classes.

Your input string is in standard ISO 8601 format. So no need to specify a formatting pattern for parsing.

LocalDate ld = LocalDate.parse( "2011-12-15" );  // Parses standard ISO 8601 format by default.
Locale l = new Locale( "en" , "IN" ) ;  // English in India.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.LONG )
                                       .withLocale( l );
String output = ld.format( f );

Dump to console.

System.out.println( "ld.toString(): " + ld );
System.out.println( "output: " + output );

ld.toString(): 2011-12-15

output: 15 December 2011

See live code in IdeOne.com .


About java.time

The 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 .

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

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The 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 .

m in SimpleDateFormat stands for minutes, while M stands for month. Thus your first format should be yyyy-MM-dd .

Well this may not be your case but may help someone. In my case after conversion, day of month and month set 1. So whatever date is, after conversion i get 1 jan which is wrong. After struggling i found that in date format i have used YYYY instead of yyyy . When i changed all caps Y to y it works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM