In this topic, we will explore about to change date format in Java programming. It provides flexible and effective methods and functions to change date format in Java.
Change Date Format
Table of Contents:
- Introduction
- Program
- Output
- Conclusion
Introduction:
To change date format in Java has more flexible methods and functions.
We typically follow the methods:
- Parse the Date: If you have a date in string format, you first parse it into a
Date
object using a ‘SimpleDateFormat'
. - Format the Date: Once you have a
Date
object, you can format it into a string in your desired format using another ‘SimpleDateFormat'
.
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateFormatExample { public static void main(String[] args) { String inputDateStr = "2024-07-06"; SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat outputDateFormat = new SimpleDateFormat("dd/MM/yyyy"); try { Date date = inputDateFormat.parse(inputDateStr); String outputDateStr = outputDateFormat.format(date); System.out.println("Formatted date: " + outputDateStr); } catch (ParseException e) { System.out.println("Error parsing date: " + e.getMessage()); } } }
Output:
Formatted date: 06/07/2024
SimpleDateFormat
is used to both parse strings into dates (inputDateFormat.parse()
) and format dates into strings (outputDateFormat.format()
).yyyy-MM-dd
is the format for the input date string “2024-07-06”.dd/MM/yyyy
is the desired output format for the date, which would convert “2024-07-06” to “06/07/2024”.ParseException
is handled in case the input string doesn’t match the expected format.
Conclusion:
In the conclusion, this example demonstrates how to change the format of a date in Java from one format to another using SimpleDateFormat
. Adjust the format patterns ("yyyy-MM-dd"
, "dd/MM/yyyy"
, etc.) according to your specific requirements. In Java programming provides flexible methods and functions to change date format in Java.
Thank you for visiting our site!!!….