user788171
user788171

Reputation: 17553

How to convert a time into epoch time?

Say I have a specific instant in time where I know the hour, minute, day, second, month, year, etc; how can I convert this epoch time (seconds since 1970)?

I can't use Boost, so please don't suggest a Boost solution.

Upvotes: 22

Views: 49455

Answers (5)

Khushneet
Khushneet

Reputation: 896

Sample code to convert date string in some format to unix epoch time.

struct tm tm;
double dateInEpoch;

if (strptime("06 Jul 2022", "%d %b %Y", &tm)) {
    time_t curTime;
    struct tm * timeinfo;
                
    time(&curTime );
    timeinfo = localtime(&curTime);
                
    timeinfo->tm_year = tm.tm_year
    timeinfo->tm_mon = tm.tm_mon;
    timeinfo->tm_mday = tm.tm_mday;
        
    dateInEpoch = mktime( timeinfo );
}

For date format, please visit http://www.cplusplus.com/reference/ctime/strftime/

To test epoch date, visit https://www.epochconverter.com

Upvotes: 2

ericcurtin
ericcurtin

Reputation: 1717

mktime and memset is most portable for me:

struct tm t;
memset(&t, 0, sizeof(tm)); // Initalize to all 0's
t.tm_year = 112; // This is year-1900, so 112 = 2012
t.tm_mon = 8;
t.tm_mday = 15;
t.tm_hour = 21;
t.tm_min = 54;
t.tm_sec = 13;
time_t time_since_epoch = mktime(&t);

Upvotes: 0

Laurent Winkler
Laurent Winkler

Reputation: 91

On Linux, use timegm to avoid having your local time zone subtracted:

struct tm tm;

// set tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min and tm.tm_sec

tm.tm_year -= 1900; // year start at 1900
tm.tm_mon--;        // months start at january
TIME_STAMP t = timegm(&tm);

Upvotes: 8

Adam Rosenfield
Adam Rosenfield

Reputation: 400274

Use the mktime(3) function. For example:

struct tm t = {0};  // Initalize to all 0's
t.tm_year = 112;  // This is year-1900, so 112 = 2012
t.tm_mon = 8;
t.tm_mday = 15;
t.tm_hour = 21;
t.tm_min = 54;
t.tm_sec = 13;
time_t timeSinceEpoch = mktime(&t);
// Result: 1347764053

Upvotes: 38

chrisaycock
chrisaycock

Reputation: 37930

mktime() can convert struct tm into seconds-since-Epoch.

Upvotes: 1

Related Questions