java.time
You are using terribly troublesome old date-time classes that were supplanted years ago by the java.time classes.
Define a formatting pattern to match your input.
String input = "2018-04-12T21:25:28.0000000-0700";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSSSSSX" );
Parse as an OffsetDateTime
given that your input has an offset-from-UTC but not a time zone.
OffsetDateTime odt = OffsetDateTime.parse( input , formatter );
odt.toString(): 2018-04-12T21:25:28-07:00
Understand offset-from-UTC
You asked “to apply the -7 offset”. You may be misunderstanding the meaning of the ISO 8601 format used by your input string. That "minus seven" offset of -0700
(better formatted with a colon as -07:00
) means the date and time shown represent a moment seven hours behind UTC. This offset is used by several time zones such as America/Los_Angeles
. There is no need to apply anything, as the offset is already "applied". This string means 9 PM in the evening on the 12th of April 2018 on the west coast of North America.
Perhaps what you really want is the same moment seen as UTC. In that case, you need to add seven hours, not subtract. Do not read a ISO 8601 string as an equation. A negative number means behind UTC, so add the same number of hours-minutes to get to UTC.
Furthermore, you need not do any math at all. For a UTC value, extract a 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 instant = odt.toInstant() ;
instant.toString(): 2018-04-13T04:25:28Z
The Z
on the end of an ISO 8601 string is short for Zulu
and means UTC. so we can see that 4 AM on the following day in UTC happens at the very same time as 9 PM on the west coast of North America. In other words, 9 PM in Los Angeles is simultaneously 4 AM on the following date in Iceland and the Azores and in other places with an offset-from-UTC of zero hours.
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?