Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert time in seconds from the Epoch to day of the year?

Tags:

c++

time

epoch

I have a file filled with data, one column of which is seconds from the Epoch. For reference, an example value looks like this:

1498493536984926976

I need to convert it into a day of the year. What I have so far is this piece of code, which uses this reference to convert the date into a normal readable struct and then strftime to pull the day of the year from the struct:

time_t rawtime = stol(exploded_line[2]);
std::cout << rawtime << std::endl;
struct tm date; 
date = *localtime( &rawtime );
char *buffer;
std::cout << 2 << std::endl;
strftime (buffer,sizeof(buffer),"%j",&date);

However, this code SegFaults on the strftime line! I have no idea what is causing this. I have tried initializing buffer as

char buffer[80];

and various other declarations but nothing seems to work. I've also tried ditching the buffer entirely and just using a std::string; that hasn't worked either.

Also, I am not partial to this method. If anyone else has a better method of getting the day of the year from an Epoch time, I will totally implement it.

Any help would be appreciated!

like image 683
Joseph Farah Avatar asked Dec 18 '22 06:12

Joseph Farah


2 Answers

These lines are your problem:

char *buffer;

strftime (buffer,sizeof(buffer),"%j",&date);

You've allocated a char * but it doesn't point to anything. It's just a random value, so you're passing a wild pointer into strftime(). Also, sizeof(buffer) will be the size of the pointer (4 or 8 bytes depending on your architecture), not the size of the array that buffer is supposed to point at.

Change char * buffer to char buffer[32]; or something like that.

like image 163
Rob K Avatar answered Dec 24 '22 02:12

Rob K


Based on the fact they're supposed to be epoch times, your timestamps are in nanoseconds.

1498493536984926976s = 4.749E10 years.

1498493536984926976ns = 47.49 years.

Unless your time stamps really are 34 billion years into the future, you should convert them to seconds before sending them to localtime to get a struct tm.

like image 36
lcs Avatar answered Dec 24 '22 02:12

lcs