Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get UTCTime in millisecond since January 1, 1970 in c language

Tags:

c

time.h

Is there any way to get milliseconds and its fraction part from 1970 using time.h in c language?

like image 591
Siddiqui Avatar asked Dec 23 '09 11:12

Siddiqui


People also ask

How do you convert timestamps to milliseconds?

A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta. total_seconds() * 1000 .

How do you convert epoch time to milliseconds?

Convert from human-readable date to epoch long epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds.

Is time since epoch in UTC?

In computing, Unix time (also known as Epoch time, Posix time, seconds since the Epoch, Unix timestamp or UNIX Epoch time) is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00 UTC on 1 January 1970.

Is Unix time in milliseconds?

Unix Time in Milliseconds Another option is to represent timestamps using the number of milliseconds since the Unix epoch instead of the number of seconds.


2 Answers

This works on Ubuntu Linux:

#include <sys/time.h>  ...  struct timeval tv;  gettimeofday(&tv, NULL);  unsigned long long millisecondsSinceEpoch =     (unsigned long long)(tv.tv_sec) * 1000 +     (unsigned long long)(tv.tv_usec) / 1000;  printf("%llu\n", millisecondsSinceEpoch); 

At the time of this writing, the printf() above is giving me 1338850197035. You can do a sanity check at the TimestampConvert.com website where you can enter the value to get back the equivalent human-readable time (albeit without millisecond precision).

like image 88
stackoverflowuser2010 Avatar answered Oct 20 '22 08:10

stackoverflowuser2010


If you want millisecond resolution, you can use gettimeofday() in Posix. For a Windows implementation see gettimeofday function for windows.

#include <sys/time.h>  ...  struct timeval tp; gettimeofday(&tp); long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000; 
like image 24
Plow Avatar answered Oct 20 '22 08:10

Plow