String (dd-MM-yyyy HH: mm) to Date (yyyy-MM-dd HH: mm) | Java

I have a string in "dd-MM-yyyy HH: mm" and you need to convert it to a date object in the format "yyyy-MM-dd HH: mm".

Below is the code I use to convert

oldScheduledDate = "16-05-2011 02:00:00";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date oldDate = (Date)formatter.parse(oldScheduledDate);

Now when I print oldDate, I get

Sat Nov 01 02:00:00 GMT 21What is completely wrong, what am I doing wrong here?

+3
source share
5 answers
    String dateSample = "10-01-2010 21:10:05";

    String oldFormat = "dd-MM-yyyy HH:mm:ss";
    String newFormat = "yyyy-MM-dd HH:mm:ss";

    SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
    SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);


    try {
        System.out.println(sdf2.format(sdf1.parse(dateSample)));

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
+19
source

"yyyy-MM-dd" doesn't even look the same as "16-05-2011". Hm. Well, why not?

Tips:

  • DateFormat is very literal. It accepts the specified format and uses it - nothing unusual.
  • : → ( ) → → ( ) →
  • , .
+5

but, 05-16-2011 02:00:00 AM does not match yyyy-MM-dd HH: mm: ss

+1
source

A simple approach is to swap around letters.

String s = "16-05-2011 02:00:00";
String newDate=s.substring(6,10)+s.substring(3,6)+'-'+s.substring(0,2)+s.substring(10);
+1
source

you need to use a formatter when you want to display a formatted date




public static void main(String[] args) throws ParseException {

        String oldScheduledDate = "16-05-2011 02:00:00";
        DateFormat oldFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date oldDate = (Date)oldFormatter .parse(oldScheduledDate);
        System.out.println(formatter.format(oldDate));
    }

0
source

Source: https://habr.com/ru/post/1781701/


All Articles