简体   繁体   中英

Convert date format from string

I have a string where contain date and time with format like this

"2020-09-20-08-40"

i try to convert that string to date with format "dd-MM-yyyy HH:mm" and print that in a textview. I saw other people try convert with this way

        String dateString = "2020-09-20-08-40"
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        Date date = format1.parse(dateString);
        String dateFinal = format2.format(date);
        t_date.setText(dateFinal);

when i try this way, i got error java.lang.IllegalArgumentException

How to solve this?

tl;dr

LocalDateTime.parse( 
    "2020-09-20-08-40" , 
    DateTimeFormatter.ofPattern( "uuuu-MM-dd-HH-mm" ) 
)

See code run live at IdeOne.com .

2020-09-20T08:40

Details

Avoid using terrible legacy date-time classes. Use only java.time classes.

Define a formatting pattern to match your input.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd-HH-mm" ) ;

Parse your input text.

LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

Tip: Educate the publisher of your data about the ISO 8601 standard for exchanging date-time values as text. No need to be inventing such formats as seen in your Question. The java.time classes use the standard formats by default when parsing/generating strings, so no need to specify a formatting pattern.

Thanks to @Nima Khalili and @Andre Artus answer, i can solve this. My code will look this

        String dateString = "2020-09-20-08-40" 
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
        format1.setTimeZone(TimeZone.getTimeZone("GMT + 7"));
        SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        Date date;
        try {
            date = format1.parse(dateString);
            String dateFinal = format2.format(date);
            t_date.setText(dateFinal);
        } catch (ParseException e) {
            e.printStackTrace();
        }

If you have a date+time like "2020-09-20-08-40" then your format should reflect that, eg

"yyyy-MM-dd-HH-mm"

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