Java – How to change date format in a String

If Java 8, DateTimeFormatter, else SimpleDateFormat to change the date format in a String.

1. DateTimeFormatter (Java 8)

Convert the String to LocalDateTime and change the date format with DateTimeFormatter

DateFormatExample1.java

package com.mkyong;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateFormatExample1 {

	// date format 1
    private static final DateTimeFormatter dateFormatter 
		= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
	
	// date format 2
    private static final DateTimeFormatter dateFormatterNew 
		= DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy HH:mm:ss a");

    public static void main(String[] args) {

        String date = "2019-05-23 00:00:00.0";

		// string to LocalDateTime
        LocalDateTime ldateTime = LocalDateTime.parse(date, dateFormatter);

        System.out.println(dateFormatter.format(ldateTime));

        // change date format
        System.out.println(dateFormatterNew.format(ldateTime));


    }

}

Output


2019-05-23 00:00:00.0

Thursday, May 23, 2019 00:00:00 AM

2. SimpleDateFormat

Convert the String to Date and change the date format with SimpleDateFormat

SimpleDateFormatExample.java

package com.mkyong;

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

public class SimpleDateFormatExample {

    private static final SimpleDateFormat sdf = 
			new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

    private static final SimpleDateFormat sdfNew = 
			new SimpleDateFormat("EEEE, MMM d, yyyy HH:mm:ss a");

    public static void main(String[] args) {

        String dateString = "2019-05-23 00:00:00.0";

        try {

			// string to date
            Date date = sdf.parse(dateString);

            System.out.println(sdf.format(date));
			
            System.out.println(sdfNew.format(date));

        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

}

Output


2019-05-23 00:00:00.0

Thursday, May 23, 2019 00:00:00 AM
Note
More Java String to Date examples

References

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Leo D.
1 year ago

Excellent overview. I’ve found that using a centralized date management tool is essential in multi-user platforms—especially when users operate in different regions and expect accurate time-based data and reminders

Neha
7 years ago

Could you please add some CQRS tutorials ?