If you are using at least Java 8, then you should use the date-time API. The documentation for class java.time.format.DateTimeFormatter
details the recognized pattern characters. Recommended to also indicate the Locale
.
By the way, 26th December, 2022 is a Monday and not a Wednesday. In the below code, using the example from your question, I get the following error message:
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Wed Dec 26 11:11:59 SGT 2022' could not be parsed: Conflict found: Field DayOfWeek 1 differs from DayOfWeek 3 derived from 2022-12-26
Since the example in your question contains a time zone, the below code parses the string to a ZonedDateTime
but you could also parse it to a different class, depending on your requirements – which aren't clear to me from your question.
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Doctor {
public static void main(String[] args) {
String raw = "Mon Dec 26 11:11:59 SGT 2022";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(raw, dtf);
System.out.println(zdt);
}
}
Running the above code gives following output:
2022-12-26T11:11:59+08:00[Asia/Singapore]
If you want to save the date in your database, then the data type of the column in the database table should be a [database] date type. Hence you need to use JDBC so the format is not important since you need to convert the ZonedDateTime
to a java.sql.Date
.
java.sql.Date d = java.sql.Date.valueOf(zdt.toLocalDate());
where zdt
is the value obtained in the code, above.