Suppose that my server located in USA and I live in Russia. We know that they have different time zones.
My application getting text(String
) from server. An
Time zone is irrelevant for elapsed hours-minutes-seconds.
Duration.between(
Instant.parse( "2017-12-14T01:34:56.123456789Z" ) ;
Instant.now()
)
The modern approach uses the industry-leading java.time classes. These supplant the troublesome old legacy date-time classes such as Date
and Calendar
.
Servers should generally be set to a time zone of UTC. And you should never depend on any such setting. Instead, your code should specify the desired/expected time zone.
Your business logic, data storage, and data exchange should all be in UTC as a general rule. When serializing to text, use the standard ISO 8601 formats only.
Apply other time zones when necessary, as when expected by a user in the user interface. So generally you should think of time zones other than UTC as a localization issue.
Instant
The Instant
class represents a moment, a point on the timeline in UTC with a resolution of nanoseconds. Getting the current moment is unaffected by time zone settings.
Instant instant = Instant.now() ;
Serializing to text in standard format by calling toString
.
String output = instant.toString() ;
You can exchange an Instant
with your database.
myPreparedStatement.setObject( … , instant ) ;
…and…
Instant instant = myPreparedStatement.getObject( … , Instant.class ) ;
ZonedDateTime
Apply a ZoneId
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
To generate strings in non-standard formats, use the DateTimeFormatter
class. Search Stack Overflow for many examples and discussions.
Duration
To get the number of hours, minutes, seconds elapsed, use the Duration
class. Note that you do not need time zones for elapsed time; UTC (Instant
) gives the same result.
Duration d = Duration.between( then , Instant.now() ) ;
For earlier Android, see the ThreeTen-Backport and ThreeTenABP projects. See How to use….
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?