Format from Aug 14 to YYYYMMDD

Change the date of August 14, 2011 to the format 20110814 .. how can I do this in java?

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

+3
source share
4 answers
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String yyyyMMdd = sdf.format(date);

Link: java.text.SimpleDateFormat

Update: The issue of the Elite Gentleman is important. If you start with a symbol String, you must first analyze it to get an object datefrom the above example:

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

While the example provided by Bojo is good for English, it may not work in other locales (as long as “aug” is not the name of the month in another locale). For my environment with polish locales, I would prefer to use something like:

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

ParsePosition, ( date null) , - .

+1

2011 , . . SimpleDateFormat Date. java.time:

    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));

:

20110814

, , , . , , A , , , . parseCaseInsensitive(). , appendPattern().

: "14aug" . SimpleDateFormat 1970 ( ), , . , :

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

, , :

20170814

2: , DateTimeFormatter.BASIC_ISO_DATE , .

+1

Ole V.V. . java.time, (Date Calendar).

MonthDay

, : MonthDay.

DayeTimeFormatterBuilder , . 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

, ISO 8601 --MM-DD -, . java.time, MonthDay, , . : MonthDay md = MonthDay.parse( "--08-11" ) ;.

, . , LocalDate.

LocalDate ld = md.atYear( 2011 ) ; 

ld.toString(): 2011-08-11

ISO 8601. "" , . DateTimeFormatter.BASIC_ISO_DATE.

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

20110811

+1

All Articles