I have this date format coming from Twitter API: Wed Oct 11 17:30:20 CEST 2017
In Java SQL I need this date format: 2017-10-11 17:30:20
How can i convert the date format to make it possible to insert into database?
This i my code:
Date createdAt = message.getCreatedAt();
2
Answers
Well, it seems
getCreatedAt()
method returns ajava.util.Date
object, so if you need to instantiate ajava.sql.Date
instance to save on your database, you can simply do this:http://twitter4j.org/javadoc/twitter4j/Status.html#getCreatedAt–
tl;dr
Use objects, not strings.
java.time
With JDBC 4.2 and later, you can directly exchange java.time objects with the database. No need to mess about with mere strings nor the troublesome old legacy date-time classes such as
java.sql.Date
/java.sql.Timestamp
.Define a formatting pattern for your input. Specify a
Locale
to indicate the human language needed for translating the name of the day and name of the month.Parse as a
ZonedDateTime
given that your input includes a hint about the time zone. Note that yourCEST
is not actually a time zone, butZonedDateTime
will take a guess at interpreting. Such 3-4 letter pseudo-zones give a hint about the time zone, but are not standardized and are not even unique(!). This, along with the rest of your input string, is a terrible choice of date-time formats. Whenever possible, use standard ISO 8601 formats instead.Specify a proper time zone name in the format of
continent/region
, such asAmerica/Montreal
,Africa/Casablanca
, orPacific/Auckland
.Generally best to work in UTC. Extract a
Instant
object. TheInstant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).Pass that to your database via JDBC driver supporting JDBC 4.2 or later.
Retrieval:
If your database column is of the type
TIMESTAMP WITHOUT TIME ZONE
rather thanTIMESTAMP WITH TIME ZONE
, then use aLocalDateTime
object rather than aZonedDateTime
/Instant
. ALocalDateTime
object lacks any concept of time zone or offset-from-UTC.Legacy
java.util.Date
If your Twitter call actually returned a
java.util.Date
object rather than a String, convert to an Instant and follow the test of the steps seen above.About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.