How to Assign Values to Java Date Objects
In Java, you can use the SimpleDateFormat class to convert a date string to a Date type, or convert a Date type to the corresponding formatted date string. Here is an example code:
- Convert a date string to a Date type.
String dateString = "2021-12-31";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(dateString);
- convert a Date type to a date string
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = sdf.format(date);
In the example given above, the constructor of the SimpleDateFormat class accepts a pattern string for the date format as a parameter, allowing for the definition of different date formats as needed. This can be achieved by calling the parse method to convert a date string into a Date type, or by calling the format method to convert a Date type into a date string.