Capturing a Time in Milliseconds

Capturing a time in milliseconds

To have millisecond precision you have to use system calls specific to your OS.

In Linux you can use

#include <sys/time.h>

timeval tv;
gettimeofday(&tv, 0);
// then convert struct tv to your needed ms precision

timeval has microsecond precision.

In Windows you can use:

#include <Windows.h>

SYSTEMTIME st;
GetSystemTime(&st);
// then convert st to your precision needs

Of course you can use Boost to do that for you :)

How to get current timestamp in milliseconds since 1970 just the way Java gets

If you have access to the C++ 11 libraries, check out the std::chrono library. You can use it to get the milliseconds since the Unix Epoch like this:

#include <chrono>

// ...

using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
);

How to get milliseconds in c++?

With C++ 11, using std::chrono library.

#include <iostream>
#include <chrono>

int main()
{

auto now = std::chrono::system_clock::now();

std::chrono::milliseconds ms_since_epoch = std::chrono::duration_cast< std::chrono::milliseconds >(now.time_since_epoch());
std::chrono::seconds seconds_since_epoch = std::chrono::duration_cast< std::chrono::seconds >(now.time_since_epoch());

std::cout << (ms_since_epoch - seconds_since_epoch).count() << std::endl;

return 0;
}

On seconds thought, modulo 1000 would have done the same as subtracting the seconds.
Anyway, given that the epoch is canonical (has 00 for seconds and 000 for milliseconds), that part of it is indeed the actual milliseconds measurement of the now moment.

Give timestamp in milliseconds how do I find out if it is older than 2 days

tl;dr

Instant                              // Represents a moment as seen in UTC.
.ofEpochMilli( yourCount ) // Convert a count of milliseconds since 1970-01-01T00:00Z to an `Instant` object.
.isBefore( // Compares one `Instant` object to another.
Instant
.now() // Capture the current moment as seen in UTC (an offset of zero).
.minus( // Instantiate another `Instant` object for another moment, per immutable objects pattern.
Duration.ofHours( 48 ) // Define a span-of-time, not attached to the timeline, on a scale of hours-minutes-seconds.
) // Returns another `Instant` object.
) // Returns `boolean` primitive.

Question 1

How do I find out if this is older than 2 days in my code .?

Parse your System.currentTimeMillis() long integer number as a Instant.

Instant instant = Instant.ofEpochMilli( 1_628_125_542_977L ) ;

You want to go back 48 hours apparently.

Duration fortyEightHours = Duration.ofHours( 48 ) ;
Instant ago48Hours = Instant.now().minus( fortyEightHours ) ;

Compare.

boolean momentIsMoreThan48HoursAgo = instant.isBefore( ago48Hours ) ;

Question 2

Is there a better way to assigning timestamp during creation instead of using system.currentTimeMillis ?

Yes, the better way is Instant.

Instead of System.currentTimeMillis() I suggest you just work with Instant class. Depending on the Java implementation, you can expect to capture the current moment with a resolution of either milliseconds on microseconds.

Instant now = Instant.now() ;
String outputIso8601 = now.toString() ;
long millisSinceEpoch = now.toEpochMilli() ;

Unless you have an extreme need for compact data, I suggest you serialize date-time values using strings in standard ISO 8601 format rather than as mysterious numbers.

For the current moment, the format would be: 2021-08-04T23:06:06Z where T separates the year-month-day from the time-of-day, and the Z means +00:00 an offset-from-UTC of zero.

Question 3

Is not is System.currentTimeMillis() machine agnostic and does it give UTC time ?

I do not know what you mean by "machine agnostic". That call does track time, and it does depend on the hardware clock of your host computer being set correctly.

As for UTC time, yes the method System.currentTimeMillis() is documented as returning the number of milliseconds (give or take, depending on resolution of host computer’s hardware clock) since the epoch reference of first moment of 1970 as seen with an offset-from-UTC of zero hours-minutes-seconds, 1970-01-01T00:00Z, while ignoring leap seconds.

The Instant class does the same, but can represent a moment with the finer granularity of nanoseconds rather than milliseconds. For capturing the current moment, conventional computer hardware clocks are currently accurate only to range of milliseconds to microseconds, not nanoseconds.


All of this has been covered many many times already on Stack Overflow. Search to learn more.

How to convert a specific time to milliseconds

tl;dr

LocalTime.now()                               // Capture current moment. Better to explicitly pass a `ZoneId` object than rely implicitly on the JVM’s current default time zone.
.isBefore( LocalTime.of( 18 , 0 ) ) // Compare the current time-of-day against the limit.

No need for milliseconds count

No need to count milliseconds. Java has smart date-time classes for this work, found in the java.time package built into Java 8 and later. For earlier Android, see the last bullets below.

No need for System.currentTimeMillis(). The java.time classes do the same job.

LocalTime

To get the current time of day, without a date and without a time zone, use LocalTime.

Determining the current time requires a time zone. For any given moment, the time-of-day varies by zone. If omitted, the JVM’s current default time zone is applied implicitly. Better to explicitly specify your desired/expected time zone, as the default may change at any moment before or during runtime.

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( "Africa/Tunis" ) ;
LocalTime now = LocalTime.now( z ) ;

Compare with methods isBefore, isAfter, and equals.

A shorter way of asking "is equal to or later than noon" is "is not before noon".

boolean isAfternoon = 
( ! now.isBefore( LocalTime.NOON ) )
&&
now.isBefore( LocalTime.of( 18 , 0 ) )
;

If you are concerned about the effects of anomalies such as Daylight Saving Time( DST), explore the use of ZonedDateTime instead of mere LocalTime.


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.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, and later

    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….


Related Topics



Leave a reply



Submit