tl;dr
myResultSet.getObject( // Use JDBC 4.2 or later to get *java.time* objects rather than mere strings.
… , // Specify the column in database of type `TIMESTAMP WITH TIME ZONE`.
Instant.class // Extract from database as a `Instant` object in UTC, via JDBC.
)
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust into a time zone other than UTC. Returns a `ZonedDateTime` object.
.toLocalDate() // Extract the date-only value, without time-of-day and without time zone. Returns a `LocalDate` object.
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) ) // Determine the first moment of the day (not always 00:00). Returns a `ZonedDateTime` object.
And…
Duration.between( zdtStartOfDay , zdt ) // Represent the span of time between the first moment of the day and the target moment. Each argument is a `ZonedDateTime` object here.
.toMillis() // Get entire span as a count of milliseconds. Returns a `long` primitive.
- No need for strings.
- No need for
java.sql.Timestamp
.
java.time
The modern approach uses the java.time classes that supplant the troublesome old legacy classes such as java.sql.Timestamp
& Date
& Calendar
.
The Answer by MadProgrammer is headed in the right direction by using java.time but uses the wrong class: LocalDateTime
class purposely lacks any concept of time zone or offset-from-UTC but our input string does. The Z
on the end of the input String is short for Zulu
and means UTC. Throwing away valuable information (zone/offset info) is not a good practice.
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 = Instant.parse( "2015-07-24T09:39:14.000Z" ) ;
Smart objects, not dumb strings
I have to fetch time stamp from DB and retrieve only time and compare two time.
below are the string values
Use appropriate objects to exchange data with your database, not mere strings.
As of JDBC 4.2, you can directly exchange java.time objects via getObject
& setObject
.
Instant instant = myResultSet( … , Instant.class ) ;
You just fetched a date-time directly from a database column of type similar to the SQL-standard TIMESTAMP WITH TIME ZONE
.
For sending data to the database, use a PreparedStatement
with placeholders.
myPreparedStatement.setObject( … , instant ) ;
The Instant
object retrieved via JDBC from the database is in UTC, by definition. To get the time-of-day, you must specify the wall-clock time of the region expected by the user (the time zone).
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter pseudo-zones such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
Apply that time zone to get a ZonedDateTime
object. The Instant
and the ZonedDateTime
represent the same moment, the same point on the timeline. This is a crucial concept to understand. Two friends talking on the phone, one in Québec Canada and one in Paris France will each look up to a clock on the wall simultaneously at the same moment yet see a different time in use by the people of their particular region.
ZoneDateTime zdt = instant.atZone( z ) ;
If you care only about the time-of-day, extract a LocalTime
object.
LocalTime lt = zdt.toLocalTime();
Generate a String
in standard ISO 8601 format.
String output = lt.toString();
Generate a string in localized format.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ;
String output = lt.format( f ) ;
But you seem to want a count of something since the start of the day – your Question is not clear. Perhaps you want a count of whole seconds, or milliseconds, or I don't know what.
We must get the start of the day in the desired/expected time zone. Do not assume the day starts at the time 00:00:00. Because of anomalies such as Daylight Saving Time (DST), the day may start at another time such as 01:00:00. Let java.time determine the start of the day.
ZonedDateTime zdtStartOfDay = zdt.toLocalDate().atStartOfDay( z ) ;
Calculate the elapsed span of time as a Duration
.
Duration d = Duration.between( zdtStartOfDay , zdt ) ;
Extract the entire span as a number of whole seconds.
long secondsSinceStartOfDay = d.toSeconds() ;
Extract the entire span as a number of milliseconds.
long millisSinceStartOfDay = d.toMillis() ;
Beware of data loss. The java.time classes have resolution of nanoseconds, so you are ignoring the finer parts of the value if present when you call the to…
methods.
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.