I am getting a parse exception when inserting "Thursday 01 March 2018 12:43:38 PM IST"
into MySQL as a timestamp.
How can I convert this string for insertion into a MySQL timestamp column?
I am getting a parse exception when inserting "Thursday 01 March 2018 12:43:38 PM IST"
into MySQL as a timestamp.
How can I convert this string for insertion into a MySQL timestamp column?
Without seeing your code, it's hard to tell exactly why you're getting an error, but anyway...
A parse exception usually occurs because the formatter/parser class has found a problem; either the pattern you use doesn't match the string you're trying to parse, or some config is wrong, or anything like that. So let's see it:
java.util.Locale
, otherwise it'll use the system's defaultIn Java, you could do:
// use English locale
SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd MMMM yyyy hh:mm:ss a zzz", Locale.ENGLISH);
// use India timezone
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
String s = "Thursday 01 March 2018 12:43:38 PM IST";
Date date = sdf.parse(s);
Timestamp timestamp = new Timestamp(date.getTime());
But SimpleDateFormat
is full of problems: https://eyalsch.wordpress.com/2009/05/29/sdf/
For Java 8 or higher, there's a better API for that:
// use India timezone
Set<ZoneId> preferredZones = new HashSet<>();
preferredZones.add(ZoneId.of("Asia/Kolkata"));
// use English locale
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("EEEE dd MMMM yyyy hh:mm:ss a ")
.appendZoneText(TextStyle.SHORT, preferredZones)
.toFormatter(Locale.ENGLISH);
String s = "Thursday 01 March 2018 12:43:38 PM IST";
ZonedDateTime zdt = ZonedDateTime.parse(s, formatter);
System.out.println(zdt);
Timestamp timestamp = Timestamp.from(zdt.toInstant());
Note that I used "Asia/Kolkata" as timezone. Those names in the format "Continent/City" are the standard used by Java, while short names such as "IST" are ambiguous and should be avoided. Fortunately, the API provides a way to workaround this ambiguity, but you must choose the proper zone to work with.
As a last note, keep in mind that date objects don't have a format: https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date/
When you save a Date
, Timestamp
or any other date object to a database, you're saving their values, and those dates are not in any specific format. Strings like "Thursday 01 March 2018 12:43:38 PM IST"
are just a representation of the date values, but it doesn't mean they are saved in that format.