38

Hi i have the following string:2012-05-20T09:00:00.000Z and i want to format it to be like 20/05/2012, 9am

How to do so in java?

Thanks

jmj
  • 237,923
  • 42
  • 401
  • 438
sad tater
  • 571
  • 2
  • 6
  • 9
  • Modern answer: use java.time, the modern Java date and time API. `OffsetDateTime.parse("2012-05-20T09:00:00.000Z").format(DateTimeFormatter.ofPattern("dd/MM/uuuu"))`. Or even better, use `DateTimeFormatter.ofLocalizedDate()`. – Ole V.V. Apr 17 '19 at 09:29

3 Answers3

86

If you are looking for a solution to your particular case, it would be:

Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2012-05-20T09:00:00.000Z");
String formattedDate = new SimpleDateFormat("dd/MM/yyyy, Ka").format(date);
IgorGanapolsky
  • 26,189
  • 23
  • 116
  • 147
Keppil
  • 45,603
  • 8
  • 97
  • 119
35

use SimpleDateFormat to first parse() String to Date and then format() Date to String

jmj
  • 237,923
  • 42
  • 401
  • 438
5
package newpckg;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StrangeDate {

    public static void main(String[] args) {

        // string containing date in one format
        // String strDate = "2012-05-20T09:00:00.000Z";
        String strDate = "2012-05-20T09:00:00.000Z";

        try {
            // create SimpleDateFormat object with source string date format
            SimpleDateFormat sdfSource = new SimpleDateFormat(
                    "yyyy-MM-dd'T'hh:mm:ss'.000Z'");

            // parse the string into Date object
            Date date = sdfSource.parse(strDate);

            // create SimpleDateFormat object with desired date format
            SimpleDateFormat sdfDestination = new SimpleDateFormat(
                    "dd/MM/yyyy, ha");

            // parse the date into another format
            strDate = sdfDestination.format(date);

            System.out
                    .println("Date is converted from yyyy-MM-dd'T'hh:mm:ss'.000Z' format to dd/MM/yyyy, ha");
            System.out.println("Converted date is : " + strDate.toLowerCase());

        } catch (ParseException pe) {
            System.out.println("Parse Exception : " + pe);
        }
    }
}
Arch
  • 109
  • 1
  • 3