Reputation: 5817
What's the best way determining the datetime inside a Java Thread (in Android)?
I have the following snippet:
public void repeatedlyPrintTheTime() {
final Handler handler = new Handler();
mR = new Runnable() {
public void run() {
System.out.println("Time 1 is " + mCalendar.getTime().toString());
System.out.println("Time 2 is " + GregorianCalendar.getInstance().getTime().toString());
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(mR, 1000);
}
Time 1 repeatedly prints the same time, but Time 2 updates on every iteration.
Do I really have to get a new instance of GregorianCalendar every time I want to check what the time is?
Upvotes: 1
Views: 112
Reputation: 339362
Yes, you must get a fresh date-time object instance each time you want to capture the current moment. No automatic updating of existing instance.
Instant.now()
A GregorianCalendar
holds a single moment, and is not automatically updated. If it were updating automatically, you would never be able to do any business logic as the value would constantly be changing as your code ran!
Also, GregorianCalendar
and its sibling classes are an awful mess and should be avoided. They are now legacy, supplanted by the java.time classes.
Use Instant
for the current moment in UTC. 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.now();
instant.toString(): 2017-02-27T14:48:58.664Z
To later capture the current time again, obtain another Instant
instance.
Instant instantLater = Instant.now();
instantLater.toString(): 2017-02-27T14:49:02.164Z
You can even capture the delta between them, as a Duration
object.
Duration duration = Duration.between( instant, instantLater );
duration.toString(): PT3.5S
To see that same moment through the lens of some particular region’s wall-clock time, adjust into a time zone. Apply a ZoneId
to get a ZonedDateTime
object.
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 abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2017-02-27T09:48:58.664-05:00[America/Montreal]
See this code run live at IdeOne.com.
To represent a moment in the future or the past, specify inputs to get an OffsetDateTime
or a ZonedDateTime
.
JavaDoc…
ZonedDateTime.of( int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond, ZoneId zone )
ZonedDateTime zdt = ZonedDateTime.of( 2017 , 1 , 23 , 12 , 34 , 56 , 123456789 , ZoneId.of( "America/Montreal" );
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.
Upvotes: 2
Reputation: 1144
Some calendar classes are not thread-safe. You could insert that code in a synchronized
block with a lock:
private Object calendarLock; --Class attribute
public void repeatedlyPrintTheTime() {
final Handler handler = new Handler();
mR = new Runnable() {
public void run() {
synchronized(calendarLock) {
System.out.println("Time 1 is " + mCalendar.getTime().toString());
System.out.println("Time 2 is " + GregorianCalendar.getInstance().getTime().toString());
handler.postDelayed(this, 1000);
}
}
};
handler.postDelayed(mR, 1000);
}
Upvotes: 0