How to change date format in a Java string?
To change the date format in a Java string, you can use the SimpleDateFormat
class. This class allows you to specify a pattern for the date format, and then use the format()
method to convert a Date
object to a formatted string. Here's an example:
Date date = new Date();
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat newFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String originalDate = originalFormat.format(date);
System.out.println("Original date: " + originalDate);
String newDate = newFormat.format(date);
System.out.println("New date: " + newDate);
In this example, the originalFormat
object uses the pattern "yyyy-MM-dd HH:mm:ss"
to format the date as a string in the original format, and the newFormat
object uses the pattern "dd/MM/yyyy HH:mm:ss"
to format the date as a string in the new format.
You can find a full list of the pattern letters that you can use in a SimpleDateFormat
pattern in the Java documentation.