开发者

format date from 14 aug to YYYYMMDD

Change the date 14 aug 2011 to the format开发者_JAVA百科 20110814 .. how can i do that in java ?

Here 14aug is a string ... String date="14aug";


SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String yyyyMMdd = sdf.format(date);

Reference: java.text.SimpleDateFormat

Update: the question by The Elite Gentleman is important. If you start with a String, then you should first parse it to obtain the date object from the above example:

Date date = new SimpleDateFormat("dd MMM yyyy").parse(dateString);


The other answers were good answers in 2011 when they were written. Time moves on. Today no one should use the now long outdated classes SimpleDateFormat and Date. The modern answer uses the java.time classes:

    String date = "14 aug 2011";
    DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("dd MMM uuuu")
            .toFormatter(Locale.ENGLISH);
    System.out.println(LocalDate.parse(date, parseFormatter)
                        .format(DateTimeFormatter.BASIC_ISO_DATE));

This prints the desired:

20110814

The modern parsing mechanism is somewhat stricter because experience shows that the old one was way too lenient and often produced surprising results in situations where one would have expected an error message. For example, the modern one requires correct case, that is, capital A in Aug in English, unless we tell it that it should parse without case sensitivity. So this is what I am doing with the parseCaseInsensitive(). The call affects the following builder method calls, so we have to place it before appendPattern().

Edit: Taking your string "14aug" from the question literally. SimpleDateFormat would have used 1970 as default year (year of the epoch), giving you trouble how to get the correct year. The modern classes allow you to specify a default year explicitly, for example:

    String date = "14aug";
    DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("ddMMM")
            .parseDefaulting(ChronoField.YEAR, Year.now(ZoneId.systemDefault()).getValue())
            .toFormatter(Locale.ENGLISH);

With this change, running the code today we get:

20170814

Edit 2: Now using DateTimeFormatter.BASIC_ISO_DATE for formatting as recommended in Basil Bourque’s answer.


While example given by Bozho is good for English locale it may not work in other locales (as long as "aug" is not month name in other locale). For my environment with Polish locales I would rather use something like:

ParsePosition pos = new ParsePosition(0);
Date date = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH).parse("14 aug 2011", pos);

Also note usage of ParsePosition which in case of parse problems (then date will be null) will tell you at what position parsing had troubles.


The Answer by Ole V.V. is excellent. It shows you the modern approach using java.time classes rather than the troublesome old legacy date-time classes ( Date & Calendar ).

MonthDay

I will extend that Answer by adding one thought: You can represent your input of day-of-month number and abbreviated Month name as a MonthDay object.

To understand the use of DayeTimeFormatterBuilder here, see that other Answer by Ole V.V..

String input = "11aug" ;
DateTimeFormatter f = 
    new DateTimeFormatterBuilder()  
        .parseCaseInsensitive()
        .appendPattern( "ddMMM" )
        .toFormatter( Locale.ENGLISH )
;
MonthDay md = MonthDay.parse( input , f ) ;

md.toString(): --08-11

If possible, I suggest using the ISO 8601 standard format --MM-DD for textually representing a month-day value, rather than your own custom non-standard format. The java.time classes including MonthDay use the standard formats by default when parsing and generating strings, so no need to specify a formatting pattern. To parse: MonthDay md = MonthDay.parse( "--08-11" ) ;.

Generate a date-only value by specifying your desired year. Specifically, a LocalDate object.

LocalDate ld = md.atYear( 2011 ) ; 

ld.toString(): 2011-08-11

Your desired output format happens to comply with the standard ISO 8601 formats. Your format is the “Basic” version that minimizes the use of separators. This format is already defined in DateTimeFormatter.BASIC_ISO_DATE.

String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE ) ;

20110811

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜