-1

In Android, there is a distinction between System.currentTimeMillis() and SystemClock.elapsedRealTime.

System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably.

elapsedRealtime() and elapsedRealtimeNanos() return the time since the system was booted, and include deep sleep.

Can I use Date().timeIntervalSinceNow to measure elapsed time accurately?

I tried changing the time zone on my iPhone and the default stopwatch changed by many hours, so I'm guessing that the wall clock time is being used.

Does Swift have something equivalent to SystemClock.elapsedRealTime?

BPDev
  • 397
  • 1
  • 9
  • 1
    Check out the new Swift Clock APIs, which distinguish between wall time and monotonic time. https://github.com/apple/swift-evolution/blob/main/proposals/0329-clock-instant-duration.md – Alexander Jun 23 '23 at 21:05

1 Answers1

1

Alexander posted a link in his comment to some proposed extensions to Swift dealing with different ways of measuring time. It looks like those were added in Swift 5.7. I don't have any experience with those new language extensions. (https://github.com/apple/swift-evolution/blob/main/proposals/0329-clock-instant-duration.md)

On Apple platforms you rely on the Foundation framework, which includes a simple Date object (which records an instant in time which is a Double offset from Mac epoch time, in seconds. Mac Epoch time is midnight on January 1st, 2001 in UTC.) There is also a rich set of utilities in the Foundation framework that deals with calendars and calendrical calculations. (See the Calendar class.)

You also have access to Unix functions returning monatomic times.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • It seems that the equivalent function is `ContinousClock.now`, but I think it can only be used while the app is running "This means that the instants are only comparable locally during the execution of a program." – BPDev Jun 23 '23 at 22:09
  • "Instant in time which is a Double offset from epoch time in seconds". This is not correct. Date is an offset from reference date January 1st 2001 UTC. – Leo Dabus Jun 24 '23 at 00:41
  • We're saying the same thing. It's the Mac's epoch time, which is different than UNIX epoch time, but it's still a number of seconds from an epoch time. I edited my answer to indicate the specific epoch time used. – Duncan C Jun 24 '23 at 01:05