tl;dr
Use modern java.time classes, not terrible legacy classes.
Send a string in standard ISO 8601 format.
Instant
.now()
.truncatedTo(
ChronoUnit.SECONDS
)
.toString()
Instant.now().toString(): 2018-11-27T00:57:25Z
Flawed code
This is persisted as the UTC time.
Nope, incorrect. You are not recording a moment in UTC.
DateFormat timeFormat = new SimpleDateFormat("dd-MMMM-yy HH:mm:ss");
String time = timeFormat.format(new Date()).toString() ;
You did specify a time zone in your SimpleDateFormat
class. By default that class implicitly applies the JVM’s current default time zone. So the string generated will vary at runtime.
For example, here in my current default time zone of America/Los_Angeles
it is not quite 5 PM. When I run that code, I get:
26-November-18 16:57:25
That is not UTC. UTC is several hours later, after midnight tomorrow, as shown next:
Instant.now().toString(): 2018-11-27T00:57:25.389849Z
If you want whole seconds, drop the fractional second by calling truncatedTo
.
Instant.now().truncatedTo( ChronoUnit.SECONDS ).toString(): 2018-11-27T00:57:25Z
java.time
You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes.
Instant
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant nowInUtc = Instant.now() ; // Capture the current moment in UTC.
This Instant
class is a basic building-block class of java.time. You can think of OffsetDateTime
as an Instant
plus a ZoneOffset
. Likewise, you can think of ZonedDateTime
as an Instant
plus a ZoneId
.
Never use LocalDateTime
to track a moment, as it purposely lacks any concept of time zone or offset-from-UTC.
ISO 8601
As trincot stated in his correct Answer, date-time values are best exchanged as text in standard ISO 8601 format.
For a moment in UTC, that would be either:
2018-11-27T00:57:25.389849Z
where the Z
on the end means UTC, and is pronounced “Zulu”.
2018-11-27T00:57:25.389849+00:00
where the +00:00
means an offset from UTC of zero hours-minutes-seconds, or in other words, UTC itself.
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
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.