Java Time Formatting Guide: SimpleDateFormat
In Java, the formatting of time string is achieved through the SimpleDateFormat class. This class allows you to define your desired date/time format and format date/time objects into specified string formats, or parse strings into date/time objects.
Here is a basic example of formatting a date object into a string:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println("Formatted Date: " + formattedDate);
}
}
In this example, we are using the SimpleDateFormat class to create a date formatter with the format “yyyy-MM-dd HH:mm:ss”, and then formatting the current date object into a string with this format.
You can also use the parse() method from the SimpleDateFormat class to parse a string into a date object. For example:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
String dateStr = "2021-05-20 14:30:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = sdf.parse(dateStr);
System.out.println("Parsed Date: " + date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
In this example, we are parsing the string “2021-05-20 14:30:00” into a date object using the parse() method of the SimpleDateFormat class.
In conclusion, the method of formatting time strings in Java is done using the SimpleDateFormat class. You can use it to define custom date/time formats and format date objects into specific string formats, or parse strings into date objects.