Change String Date Format from One Form to Another in Java


We can make use of the two SimpleDateFormat to convert String Date format from one form to another in Java.

Example:

package org.code2care.examples;

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

/**
 * Convert Date format from yyyy-MM-dd
 * to dd/MM/yyyy example
 * <p>
 * author: Code2care.org
 */
public class Example {

    public static void main(String... args) {

        SimpleDateFormat currentFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat desiredFormat = new SimpleDateFormat("dd/MM/yyyy");

        try {
            
            String dateString = "2023-10-18";
            Date date = currentFormat.parse(dateString);

            String formattedDate = desiredFormat.format(date);
            System.out.println("Original Date Format: " + dateString);
            System.out.println("Required Date Format: " + formattedDate);

        } catch (ParseException e) {

            System.out.println("Error occurred while converting date formats!");
            e.printStackTrace();

        }
    }

}

}

Output:
Convert Date Formats Example Java

This is not an AI-generated article but is demonstrated by a human with Java 8 on M1 Mac running macOS Sonoma 14.0.

Please support independent contributors like Code2care by donating a coffee.

Buy me a coffee!

Buy Code2care a Coffee!

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap