In Java, you can create a Date
object from a String
value using the SimpleDateFormat
class. Here’s an example of how you can do this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter {
public static void main(String[] args) {
String dateString = "2022-05-01 12:30:00";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = formatter.parse(dateString);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
In this example, we have a String
value representing a date in the format of “yyyy-MM-dd HH:mm:ss”. We create a SimpleDateFormat
object that matches the format of the String
value.
Next, we use the parse()
method of the formatter object to convert the String
value to a Date
object. This method can throw a ParseException
if the String
value cannot be parsed as a valid date, so we need to handle this exception.
Finally, we print the Date
object to the console. The output will be the date represented by the String
value as a Date
object.