how to change format of date from string date

前端 未结 4 1089
天命终不由人
天命终不由人 2021-01-29 09:27

I have date as a string like this

String date = \"11-12-2018\"

I want to change it to \"2018-12-11\"

with the same var

4条回答
  •  一生所求
    2021-01-29 10:16

    You can do this 3 ways. First is using SimpleDateFormat and Date and second using DateTimeFormatter and LocalDate and third you can use Split.

    1. Using Date and SimpleDateFormat

    String date = "11-12-2018";
    SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
    java.util.Date d = df.parse(date);
    String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
    System.out.println(finalDate);
    

    Here we have our actual date String date = "11-12-2018"; we know we want to change it to 2018-12-11

    So lets parse that date into a Date object using this code

    SimpleDateFormat df = new SimpleDateFormat("dd-mm-yyyy");
    java.util.Date d = df.parse(date);
    

    Okay so now we have a date object of our actual date, Now lets format it to our new date.

    String finalDate = new SimpleDateFormat("yyyy-MM-dd").format(d);
    

    2. Using LocalDate and DateTimeFormatter

    Alright here we define our date again and 2 DateTimeFormatter.

    DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    

    The first formatter is our old date format, and the second one is the new one that we are gonna convert the old date into.

    Alright lets use them now!

    Now we make a new LocalDate object using our oldFormatter by parsing our dateString with the oldFormatter object

    LocalDate dateTime = LocalDate.parse(date, oldFormatter);
    

    Alright now lets format it.

    String reformattedDate = dateTime.format(newFormatter);
    

    as simple as that! Here is the full code.

    String date = "11-12-2018";
    DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDate dateTime = LocalDate.parse(date, oldFormatter);
    String reformattedDate = dateTime.format(newFormatter);
    System.out.println(reformattedDate);
    

    3. Using String::Split

    Okay this part is pretty simple. Lets split the date using -

    String[] dates = date.split("-");
    

    We already know the order of the date lets format it using String::format

    String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);
    

    Here is the full code

    String date = "11-12-2018";
    String[] dates = date.split("-");
    String reformattedDate = String.format("%s-%s-%s", dates[2], dates[1], dates[0]);
    System.out.println(reformattedDate);
    

提交回复
热议问题