Convert unix timestamp to human readable date - c++

Is there a contemporary way to convert unix timestamps to a human readable date?
Since I want to circumnavigate the year 2038 problem, I want to use int64s.
I target to convert e. g. 1205812558 to
year = 2008, month = 3, day = 18,
hour = 17, minute = 18, second = 36
All I have is now
auto year = totalSeconds / secondsPerYear + 1970;
// month and day missing
auto hours = totalSeconds / 3600 % 24;
auto minutes = totalSeconds / 60 % 60;
auto seconds = totalSeconds % 60;

In C++20 (according to the draft-spec for C++20 as it stands today), you will be able to say:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
cout << sys_seconds{1205812558s} << '\n';
cout << sys_seconds{32879409516s} << '\n';
}
and it will output:
2008-03-18 03:55:58
3011-11-28 17:18:36
These are datetimes in UTC.
You can use Howard Hinnant's date library to experiment with this extended <chrono> functionality today by adding:
#include "date/date.h"
and
using namespace date;
to the above program. You can experiment online with this program here.
A comment below asks for what this looks like if the value is stored in uint64_t. The answer is that you need to convert the integral type to seconds, and then the seconds to sys_seconds:
uint64_t i = 1205812558;
cout << sys_seconds{seconds(i)} << '\n';
There do exist limits on this contemporary functionality, but they live out near the years +/-32K (far beyond the limits of the accuracy of the current civil calendar).
To be completely transparent, there do exist ways of doing this using only C++98/11/14/17, but they are more complicated than this, and are subject to multithreading bugs. This is due to the use of an antiquated C API that was designed before things like multithreading and C++ were on the horizon, and when the year 2001 was only associated with science fiction (e.g. gmtime).

Wrapper
#include <chrono>
char* get_time(time_t unix_timestamp)
{
char time_buf[80];
struct tm ts;
ts = *localtime(&unix_timestamp);
strftime(time_buf, sizeof(time_buf), "%a %Y-%m-%d %H:%M:%S %Z", &ts);
return time_buf;
}

Howard Hinnant's date library makes things pretty easy:
#include "date.h"
int main()
{
using namespace date;
time_t time = 32879409516;
auto sysTime = std::chrono::system_clock::from_time_t(time);
auto date = year_month_day(floor<days>(sysTime));
std::cout << date << "\n";
}

A good straight forward solution but could do with some minor changes:
uint32_t days = (uint32_t)floor(subt / 86400);
uint32_t hours = (uint32_t)floor(((subt - days * 86400) / 3600) % 24);
uint32_t minutes = (uint32_t)floor((((subt - days * 86400) - hours * 3600) / 60) % 60);
uint32_t seconds = (uint32_t)floor(((((subt - days * 86400) - hours * 3600) - minutes * 60)) % 60);
printf("Time remaining: %u Days, %u Hours, %u Minutes, %u Seconds\n", days, hours, minutes, seconds);

Related

Get current time of day in c++

case
I need to write a program that moves files around at times that are set in a configuration file. The time can be 00:00:01 seconds untill 24:00:00 hours. This is converted into seconds. So if somebody wants to move a file at 12:00:00 pm today, the move time is 12 * 60 * 60 = 43200 seconds. This is done every day and the program needs to check if that time is reached.
I use the chrono library to get the time now since epoch in seconds using:
auto dayInSeconds = 86400;
auto currentTime = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock().now().time_since_epoch());
auto timeWithoutDays = currentTime % dayInSeconds;
std::cout << "time in seconds today: " << timeWithoutDays.count() << std::endl;
problem
This shows me the current time since epoch in seconds. But now for example ( 13:45 Amsterdam time) it returns a number of: 42294. If I run it exactly five seconds later in a loop it returns 42299. So the counting seems to be correct. What is not correct, is that 42299 seconds is 1174 hours (42299/ 60 /60). Which should mean that is now 11:somewhat AM but its 13:32 PM. Or not? What am I doing wrong? I just need to know, how many seconds have passed since 00:00:00 this day. So i can check if the user set time is passed and stuff needs to be done.
I would like to keep using the chrono library for all sorts of reasons, but mainly because I understand that one. So if answers use that library, it would be a great help. I have a feeling i'm doing something completely stupid.
fix
For any other that seeks the same answer. I fixed it like this, it seems to work:
auto dayInSeconds = 86400;
auto amsterdamUTCPlusTime = 7200;
auto currentTime = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock().now().time_since_epoch());
auto timeWithoutDays = currentTime % dayInSeconds;
auto currentTimeInSeconds = timeWithoutDays.count() + amsterdamUTCPlusTime;
std::cout << "time in seconds today: " << currentTimeInSeconds << std::endl;
C++20 brings extensions to <chrono> to deal with timezones. It isn't shipping yet (to the best of my knowledge). But here is what it will look like:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std;
using namespace std::chrono;
zoned_time zt{"Europe/Amsterdam", floor<seconds>(system_clock::now())};
auto lt = zt.get_local_time();
auto tod = lt - floor<days>(lt);
cout << "time in seconds today: " << tod.count() << '\n';
cout << hh_mm_ss{tod} << '\n';
}
Example output:
time in seconds today: 71923
19:58:43
If your computer's local time zone setting is already set to "Europe/Amsterdam", then "Europe/Amsterdam" above can be replaced with current_zone().
This gets the current time in UTC, truncates it to seconds precision, and then pairs it with the "Europe/Amsterdam" time_zone to create a zoned_time. Then the local time is extracted from the zoned_time. The local time of day is simply the local time minus the beginning of that day (floor<days>(lt)). This is stored in tod which has type seconds. Wrapping it in a hh_mm_ss prints it out in a hh:mm:ss format.
There exists a free, open-source C++20 <chrono> preview library which can be used with C++11/14/17 to do this. To use it, it must be installed. There's a single source file to be compiled, tz.cpp, and it needs to have access to the IANA time zone database, which can be automatically downloaded with specific build settings.
The source code above must be trivially modified by adding #include "date/tz.h" and using namespace date;. In C++11 and 14, change zoned_time to zoned_seconds, and hh_mm_ss to hh_mm_ss<seconds>.
Another possibility is to build your own UTC offset calculator for just Amsterdam (assuming current rules). The advantage of this is that it can use of subset of the free, open-source C++20 <chrono> preview library which is header-only, and thus requires no installation, and does not need the IANA time zone database. That could like this:
#include "date/date.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
auto AmsterdamOffset = [](system_clock::time_point tp)
{
auto const y = year_month_day{floor<days>(tp)}.year();
auto const start = sys_days{Sunday[last]/March/y} + 1h;
auto const end = sys_days{Sunday[last]/October/y} + 1h;
if (start <= tp && tp < end)
return 2h;
return 1h;
};
auto now = floor<seconds>(system_clock::now());
auto local_now = now + AmsterdamOffset(now);
auto tod = local_now - floor<days>(local_now);
cout << "time in seconds today: " << tod.count() << '\n';
cout << hh_mm_ss{tod} << '\n';
}
This program hardcodes the fact that Amsterdam daylight saving begins on the last Sunday of March at 01:00:00 UTC and ends on the last Sunday of October at 01:00:00 UTC.
After that, the program logic is much like the C++20 solution shown above. In C++11, 1h and 2h will have to be changed to hours{1} and hours{2} respectively.
And yet another approach: Posix time zones
There is also a Posix time zone library at this link in ptz.h. This is also a header-only library, so no install issues. It allows you to use the C++20 zoned_time combined with Posix time zones. This will give you the same results as the example above with the "hard coded" rules for Amsterdam (which are valid back through 1978).
#include "date/ptz.h"
#include <chrono>
#include <iostream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
// Amsterdam rules
Posix::time_zone tz{"CET-1CEST,M3.5.0,M10.5.0/3"};
zoned_time zt{tz, floor<seconds>(system_clock::now())};
auto lt = zt.get_local_time();
auto tod = lt - floor<days>(lt);
cout << "time in seconds today: " << tod.count() << '\n';
cout << hh_mm_ss{tod} << '\n';
}
The above assumes C++17. If in C++11 or 14 the syntax becomes a little messier:
zoned_time<seconds, Posix::time_zone> zt{tz, floor<seconds>(system_clock::now())};
The Posix::time_zone is not part of the C++20 <chrono> library, but is compatible with it. It can be used with the C++20 std::chrono::zoned_time class template as shown above.
You can use localtime function and get the current time from system.
int getIntTime()
{
struct timeb now;
struct tm *curtime;
curtime = localtime(&now);
return(curtime->tm_hour * 10000L + curtime->tm_min * 100L + curtime->tm_sec);
}
And also you should convert the set time in confgi file to same as output of this function and compare them as follow:
if(getIntTime() >= converted_time_configfile )
{
//do processing
}

Read time from string as GMT in C++

I am writing current GMT time as string as follow :
const std::time_t now = std::time(nullptr);
std::stringstream ss;
ss << std::put_time(std::gmtime(&now), "%Y-%m-%d %H:%M:%S");
Later I want to do the reverse operation, reading time from the stringstream as GMT, and compare it to current timestamp :
std::tm tm = {};
ssTimestamp >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
const std::time_t&& time = std::mktime(&tm);
const double timestampDiff((std::difftime(std::time(nullptr), time)));
Something is missing in the code below, because the decoded time is never converted to GMT, thus I end up with 1 hour time difference due to my local timezone
P.S : Can use only standard libraries, and can' t change date string format
The C++20 spec has a convenient way to do this:
using namespace std::chrono;
sys_seconds tp;
ssTimestamp >> parse("%Y-%m-%d %H:%M:%S", tp);
std::time_t time = system_clock::to_time_t(tp);
No vendor has yet implemented this part of C++20, but there is an example implementation here in namespace date.
There is no library support to do this operation in C++ prior to C++20.
The best you can do using only standard libraries is to parse the fields into a tm using std::get_time (as your question shows), and then convert that {y, m, d, h, M, s} structure to a time_t using your own math, and the assumption (which is generally true) that std::time_t is Unix Time with a precision of seconds.
Here is a collection of public domain calendrical algorithms to help you do that. This is not a 3rd party library. It is a cookbook for writing your own date library.
For example:
#include <ctime>
std::time_t
to_time_t(std::tm const& tm)
{
int y = tm.tm_year + 1900;
unsigned m = tm.tm_mon + 1;
unsigned d = tm.tm_mday;
y -= m <= 2;
const int era = (y >= 0 ? y : y-399) / 400;
const unsigned yoe = static_cast<unsigned>(y - era * 400); // [0, 399]
const unsigned doy = (153*(m + (m > 2 ? -3 : 9)) + 2)/5 + d-1; // [0, 365]
const unsigned doe = yoe * 365 + yoe/4 - yoe/100 + doy; // [0, 146096]
return (era * 146097 + static_cast<int>(doe) - 719468)*86400 +
tm.tm_hour*3600 + tm.tm_min*60 + tm.tm_sec;
}
The link above has a very in-depth description of this algorithm and unit tests to make sure it works over a range of +/- millions of years.
The above to_time_t is essentially a portable version of timegm that ships on linux and bsd platforms. This function is also called _mkgmtime on Windows.
The tm struct doesn't store the timezone information, it's mktime that by default uses the local timezone.
Following this thread, the best option would be to use:
#include "time.h"
timestamp = mktime(&tm) - timezone; //or _timezone
if timezone or _timezone is available to your compiler. A comment in the linked answer warns that it may raise issues with daylight saving time, but it should not apply to GMT.
I recently tried to solve a very similar problem. I was trying to convert a string to a specific timezone regardless what is the current timezone of a computer. Here is the solution that I came up with and works as expected:
std::time_t from_time_str(std::string time_str) {
std::stringstream ss;
std::tm tm = {};
ss << time_str;
ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
std::time_t t = std::mktime(&tm);
std::tm* gm_tm = std::gmtime(&t);
gm_tm->tm_isdst = false;
std::time_t gm_t = std::mktime(gm_tm);
std::time_t gm_offset = (gm_t - t);
std::time_t real_gm_t = t - gm_offset;
return real_gm_t;
}
The idea is use the function gmtime to get the gmtime of the timestamp so we could calculate the offset of the target computer's timezone. We then subtract the offset to get the GM time.
Note that the line gm_tm->tm_isdst = false; is required for any timezone that has daylight saving is enable, otherwise the gmtime is calculated with daylight saving offset (1 hour off) and this should not be the desired effect of calculating the actual GM time.

mktime() gives different results than Howard Hinnant's date library (std::chrono based)

I am using Howard Hinnant's date C++ library (https://howardhinnant.github.io/date/date.html), but I have some confusions using it. Below is a program where I use this library to print the year-month-day of the 3rd Friday of Nov 2017. The date::year_month_weekday class, when used with date::sys_days(), shows a correct date (Nov 17, 2017), but when I convert it to struct tm with std::chrono::system_clock::to_time_t, the results stored in this tm becomes Nov 16, 2017. I tested other cases, it seems struct tm converted from date::year_month_weekday always one day behind. Did I miss something in my program? The program is listed as below, C++ 11 is needed to compile it.
#include <iostream>
#include <chrono>
#include <sys/time.h>
#include "date.h"
using namespace std;
using namespace std::chrono;
using namespace date;
int main(int argc, char *argv[]) {
date::year y(2017);
date::month m(11);
date::weekday wd((unsigned)5);
date::weekday_indexed wi(wd,3);
date::year_month_weekday dmwd(y, m, wi);
std::cout << date::sys_days(dmwd) << std::endl; //prints 2017-11-17, which is the 3rd Friday of Nov 2017
time_t tt = std::chrono::system_clock::to_time_t(date::sys_days(dmwd));
struct tm tm1;
localtime_r(&tt, &tm1);
std::cout << "tm1.tm_year = " << tm1.tm_year << std::endl;
std::cout << "tm1.tm_mon = " << tm1.tm_mon << std::endl;
std::cout << "tm1.tm_mday = " << tm1.tm_mday << std::endl; //prints 16 instead of 17, one day behind. tm.mday is from 1 to 31.
return 0;
}
The output of this program is as follows
2017-11-17
tm1.tm_year = 117 <-- 117+1900=2017
tm1.tm_mon = 10 <-- tm_mon starts form 0, so 10 means November
tm1.tm_mday = 16 <-- tm_mday starts from 1, so 16 is the 16-th day in a month
Howard Hinnant's date.h tracks Unix Time which for most practical purposes is UTC. At this same GitHub repository there is also a timezone library if you need to deal with your local time, or with any timezone other than UTC.
So yes, as Freddie Chopin noted in the comments, you are seeing the effects of localtime_r taking your computer's local timezone into account.
You can add any time of day to sys_days that you want. sys_days is a std::chrono::time_point, but with days precision. So once you have sys_days, you are actually within the <chrono> library now, instead of the date library:
system_clock::time_point t = date::sys_days(dmwd) + 6h + 53min + 4s + 123us:

Convert Windows Filetime to second in Unix/Linux

I have a trace file that each transaction time represented in Windows filetime format. These time numbers are something like this:
128166372003061629
128166372016382155
128166372026382245
Would you please let me know if there are any C/C++ library in Unix/Linux to extract actual time (specially second) from these numbers ? May I write my own extraction function ?
it's quite simple: the windows epoch starts 1601-01-01T00:00:00Z. It's 11644473600 seconds before the UNIX/Linux epoch (1970-01-01T00:00:00Z). The Windows ticks are in 100 nanoseconds. Thus, a function to get seconds from the UNIX epoch will be as follows:
#define WINDOWS_TICK 10000000
#define SEC_TO_UNIX_EPOCH 11644473600LL
unsigned WindowsTickToUnixSeconds(long long windowsTicks)
{
return (unsigned)(windowsTicks / WINDOWS_TICK - SEC_TO_UNIX_EPOCH);
}
FILETIME type is is the number 100 ns increments since January 1 1601.
To convert this into a unix time_t you can use the following.
#define TICKS_PER_SECOND 10000000
#define EPOCH_DIFFERENCE 11644473600LL
time_t convertWindowsTimeToUnixTime(long long int input){
long long int temp;
temp = input / TICKS_PER_SECOND; //convert from 100ns intervals to seconds;
temp = temp - EPOCH_DIFFERENCE; //subtract number of seconds between epochs
return (time_t) temp;
}
you may then use the ctime functions to manipulate it.
(I discovered I can't enter readable code in a comment, so...)
Note that Windows can represent times outside the range of POSIX epoch times, and thus a conversion routine should return an "out-of-range" indication as appropriate. The simplest method is:
... (as above)
long long secs;
time_t t;
secs = (windowsTicks / WINDOWS_TICK - SEC_TO_UNIX_EPOCH);
t = (time_t) secs;
if (secs != (long long) t) // checks for truncation/overflow/underflow
return (time_t) -1; // value not representable as a POSIX time
return t;
New answer for old question.
Using C++11's <chrono> plus this free, open-source library:
https://github.com/HowardHinnant/date
One can very easily convert these timestamps to std::chrono::system_clock::time_point, and also convert these timestamps to human-readable format in the Gregorian calendar:
#include "date.h"
#include <iostream>
std::chrono::system_clock::time_point
from_windows_filetime(long long t)
{
using namespace std::chrono;
using namespace date;
using wfs = duration<long long, std::ratio<1, 10'000'000>>;
return system_clock::time_point{floor<system_clock::duration>(wfs{t} -
(sys_days{1970_y/jan/1} - sys_days{1601_y/jan/1}))};
}
int
main()
{
using namespace date;
std::cout << from_windows_filetime(128166372003061629) << '\n';
std::cout << from_windows_filetime(128166372016382155) << '\n';
std::cout << from_windows_filetime(128166372026382245) << '\n';
}
For me this outputs:
2007-02-22 17:00:00.306162
2007-02-22 17:00:01.638215
2007-02-22 17:00:02.638224
On Windows, you can actually skip the floor, and get that last decimal digit of precision:
return system_clock::time_point{wfs{t} -
(sys_days{1970_y/jan/1} - sys_days{1601_y/jan/1})};
2007-02-22 17:00:00.3061629
2007-02-22 17:00:01.6382155
2007-02-22 17:00:02.6382245
With optimizations on, the sub-expression (sys_days{1970_y/jan/1} - sys_days{1601_y/jan/1}) will translate at compile time to days{134774} which will further compile-time-convert to whatever units the full-expression requires (seconds, 100-nanoseconds, whatever). Bottom line: This is both very readable and very efficient.
The solution that divides and adds will not work correctly with daylight savings.
Here is a snippet that works, but it is for windows.
time_t FileTime_to_POSIX(FILETIME ft)
{
FILETIME localFileTime;
FileTimeToLocalFileTime(&ft,&localFileTime);
SYSTEMTIME sysTime;
FileTimeToSystemTime(&localFileTime,&sysTime);
struct tm tmtime = {0};
tmtime.tm_year = sysTime.wYear - 1900;
tmtime.tm_mon = sysTime.wMonth - 1;
tmtime.tm_mday = sysTime.wDay;
tmtime.tm_hour = sysTime.wHour;
tmtime.tm_min = sysTime.wMinute;
tmtime.tm_sec = sysTime.wSecond;
tmtime.tm_wday = 0;
tmtime.tm_yday = 0;
tmtime.tm_isdst = -1;
time_t ret = mktime(&tmtime);
return ret;
}
Assuming you are asking about the FILETIME Structure, then FileTimeToSystemTime does what you want, you can get the seconds from the SYSTEMTIME structure it produces.
Here's essentially the same solution except this one encodes negative numbers from Ldap properly and lops off the last 7 digits before conversion.
public static int LdapValueAsUnixTimestamp(SearchResult searchResult, string fieldName)
{
var strValue = LdapValue(searchResult, fieldName);
if (strValue == "0") return 0;
if (strValue == "9223372036854775807") return -1;
return (int)(long.Parse(strValue.Substring(0, strValue.Length - 7)) - 11644473600);
}
If somebody need convert it in MySQL
SELECT timestamp,
FROM_UNIXTIME(ROUND((((timestamp) / CAST(10000000 AS UNSIGNED INTEGER)))
- CAST(11644473600 AS UNSIGNED INTEGER),0))
AS Converted FROM events LIMIT 100
Also here's a pure C#ian way to do it.
(Int32)(DateTime.FromFileTimeUtc(129477880901875000).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
Here's the result of both methods in my immediate window:
(Int32)(DateTime.FromFileTimeUtc(long.Parse(strValue)).Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
1303314490
(int)(long.Parse(strValue.Substring(0, strValue.Length - 7)) - 11644473600)
1303314490
DateTime.FromFileTimeUtc(long.Parse(strValue))
{2011-04-20 3:48:10 PM}
Date: {2011-04-20 12:00:00 AM}
Day: 20
DayOfWeek: Wednesday
DayOfYear: 110
Hour: 15
InternalKind: 4611686018427387904
InternalTicks: 634389112901875000
Kind: Utc
Millisecond: 187
Minute: 48
Month: 4
Second: 10
Ticks: 634389112901875000
TimeOfDay: {System.TimeSpan}
Year: 2011
dateData: 5246075131329262904

Converting epoch time to "real" date/time

What I want to do is convert an epoch time (seconds since midnight 1/1/1970) to "real" time (m/d/y h:m:s)
So far, I have the following algorithm, which to me feels a bit ugly:
void DateTime::splitTicks(time_t time) {
seconds = time % 60;
time /= 60;
minutes = time % 60;
time /= 60;
hours = time % 24;
time /= 24;
year = DateTime::reduceDaysToYear(time);
month = DateTime::reduceDaysToMonths(time,year);
day = int(time);
}
int DateTime::reduceDaysToYear(time_t &days) {
int year;
for (year=1970;days>daysInYear(year);year++) {
days -= daysInYear(year);
}
return year;
}
int DateTime::reduceDaysToMonths(time_t &days,int year) {
int month;
for (month=0;days>daysInMonth(month,year);month++)
days -= daysInMonth(month,year);
return month;
}
you can assume that the members seconds, minutes, hours, month, day, and year all exist.
Using the for loops to modify the original time feels a little off, and I was wondering if there is a "better" solution to this.
Be careful about leap years in your daysInMonth function.
If you want very high performance, you can precompute the pair to get to month+year in one step, and then calculate the day/hour/min/sec.
A good solution is the one in the gmtime source code:
/*
* gmtime - convert the calendar time into broken down time
*/
/* $Header: gmtime.c,v 1.4 91/04/22 13:20:27 ceriel Exp $ */
#include <time.h>
#include <limits.h>
#include "loc_time.h"
struct tm *
gmtime(register const time_t *timer)
{
static struct tm br_time;
register struct tm *timep = &br_time;
time_t time = *timer;
register unsigned long dayclock, dayno;
int year = EPOCH_YR;
dayclock = (unsigned long)time % SECS_DAY;
dayno = (unsigned long)time / SECS_DAY;
timep->tm_sec = dayclock % 60;
timep->tm_min = (dayclock % 3600) / 60;
timep->tm_hour = dayclock / 3600;
timep->tm_wday = (dayno + 4) % 7; /* day 0 was a thursday */
while (dayno >= YEARSIZE(year)) {
dayno -= YEARSIZE(year);
year++;
}
timep->tm_year = year - YEAR0;
timep->tm_yday = dayno;
timep->tm_mon = 0;
while (dayno >= _ytab[LEAPYEAR(year)][timep->tm_mon]) {
dayno -= _ytab[LEAPYEAR(year)][timep->tm_mon];
timep->tm_mon++;
}
timep->tm_mday = dayno + 1;
timep->tm_isdst = 0;
return timep;
}
The standard library provides functions for doing this. gmtime() or localtime() will convert a time_t (seconds since the epoch, i.e.- Jan 1 1970 00:00:00) into a struct tm. strftime() can then be used to convert a struct tm into a string (char*) based on the format you specify.
see: http://www.cplusplus.com/reference/clibrary/ctime/
Date/time calculations can get tricky. You are much better off using an existing solution rather than trying to roll your own, unless you have a really good reason.
An easy way (though different than the format you wanted):
std::time_t result = std::time(nullptr);
std::cout << std::asctime(std::localtime(&result));
Output:
Wed Sep 21 10:27:52 2011
Notice that the returned result will be automatically concatenated with "\n".. you can remove it using:
std::string::size_type i = res.find("\n");
if (i != std::string::npos)
res.erase(i, res.length());
Taken from: http://en.cppreference.com/w/cpp/chrono/c/time
time_t t = unixTime;
cout << ctime(&t) << endl;
This code might help you.
#include <iostream>
#include <ctime>
using namespace std;
int main() {
// current date/time based on current system
time_t now = time(0);
// convert now to string form
char* dt = ctime(&now);
cout << "The local date and time is: " << dt << endl;
// convert now to tm struct for UTC
tm *gmtm = gmtime(&now);
dt = asctime(gmtm);
cout << "The UTC date and time is:"<< dt << endl;
}
To convert a epoch string to UTC
string epoch_to_utc(string epoch) {
long temp = stol(epoch);
const time_t old = (time_t)temp;
struct tm *oldt = gmtime(&old);
return asctime(oldt);
}
and then it can be called as
string temp = "245446047";
cout << epoch_to_utc(temp);
outputs:
Tue Oct 11 19:27:27 1977
If your original time type is time_t, you have to use functions from time.h i.e. gmtime etc. to get portable code. The C/C++ standards do not specify internal format (or even exact type) for the time_t, so you cannot directly convert or manipulate time_t values.
All that is known is that time_t is "arithmetic type", but results of arithmetic operations are not specified - you cannot even add/subtract reliably. In practice, many systems use integer type for time_t with internal format of seconds since epoch, but this is not enforced by standards.
In short, use gmtime (and time.h functionality in general).