Home > Software design >  Convert date format from string
Convert date format from string

Time:03-02

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?

CodePudding user response:

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.

CodePudding user response:

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");
        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();
        }

CodePudding user response:

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

"yyyy-MM-dd-HH-mm"

CodePudding user response:

Try this :

String dateString = "2020-09-20 08:40";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = null;
try {
    date = format1.parse(dateString);
} catch (ParseException e) {
    e.printStackTrace();
}
String dateFinal = format1.format(date);
t_date.setText(dateFinal);
  • Related