Reputation: 179
I am trying to convert java String date
into java.sql.Timestamp
. I am able to convert this by using SimpleDateFormat
with String date
value as "2021-01-07 02:02:16.172"
, but when trying with the value as "2021-08-04T00:00:00.000"
with seperator 'T'
, it gives me error. Below is the java code:
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws ParseException {
//String date = "2021-08-04T00:00:00.000Z";// How to convert this?
String date = "2021-01-07 02:02:16.172";// conversion successful
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date parsedDate = dateFormat.parse(date);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
System.out.println(timestamp);
}
}
Upvotes: 0
Views: 108
Reputation: 18588
You could use the modern API for dates, times and related information (like offsets from UTC): java.time
String
s in different formats need to be handled differently:
your first example String
is formatted in ISO standard, so it can be parsed without defining a custom format. The parsing implicitly uses a DateTimeFormatter.ISO_OFFSET_DATE_TIME
, which will result in an OffsetDateTime
your seconds String
lacks the 'T'
between date and time as well as an offset, that means you can just directly parse it to a LocalDateTime
java.sql.Timestamp
got methods for conversion to java.time
classes, at least to/from an Instant
and a LocalDateTime
. Since an Instant
is a well defined moment in time, you can derive it from an OffsetDateTime
:
public static void main(String[] args) throws Exception {
// your two example datetimes
String isoDateTime = "2021-08-04T00:00:00.000Z";
String customDateTime = "2021-01-07 02:02:16.172";
// you will need a custom formatter for the second one
DateTimeFormatter customDtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
// parse the Strings to java.time objects
// ISO standard, no extra formatter needed for the first one
OffsetDateTime odt = OffsetDateTime.parse(isoDateTime);
// the second one requires the formatter defined above
LocalDateTime ldt = LocalDateTime.parse(customDateTime, customDtf);
// convert them into Timestamps
Timestamp tsOne = Timestamp.from(odt.toInstant());
Timestamp tsTwo = Timestamp.valueOf(ldt);
// and print them
System.out.println("First Timestamp: " + tsOne);
System.out.println("Second Timestamp: " + tsTwo);
}
The output of this is
First Timestamp: 2021-08-04 02:00:00.0
Second Timestamp: 2021-01-07 02:02:16.172
This would be the new style...
Upvotes: 5
Reputation: 4292
new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
would be the old style
Upvotes: 1