2

I have a function which returns a timestamp in unix time as int.

I need to convert this int to a string dd/mm/yy in local time. The "local" part is causing me problems, if it weren't for that, I could have just made my own function to convert it.

I have searched around , and it seems the ctime class from the standard library would be ideal for this, in a manner like this:

int unixtime;

std::cout << std::asctime(std::localtime(unixtime));

Sadly, only *time_t is accepted. Is there any way I can convert int into this format, or any better way to get local time from unix time as int?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user129186
  • 1,156
  • 2
  • 14
  • 30

5 Answers5

1

time_t is by definition an arithmetic type, you can just do:

time_t ts = unixtime;
std::cout << std::asctime(std::localtime(&ts));
filmor
  • 30,840
  • 6
  • 50
  • 48
0
'/* localtime example */
#include <stdio.h>      /* puts, printf */
#include <time.h>       /* time_t, struct tm, time, localtime */

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time (&rawtime);
  timeinfo = localtime (&rawtime);
  printf ("Current local time and date: %s", asctime(timeinfo));

  return 0;
}'

You can simply use type time_t it will give you the time.

smali
  • 4,687
  • 7
  • 38
  • 60
0

"The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar time. When interpreted as an absolute time value, it represents the number of seconds elapsed since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)."

sources:

0

To print current time in dd/mm/yy, you may try the following:

#include <iostream>
#include <ctime>

int main(int argc, const char** argv)
{
    char date_buff[40];
    time_t time_value = time(0);
    struct tm* my_tm = localtime(&time_value);
    strftime(date_buff, sizeof(date_buff), "%d/%m/%y\n", my_tm);
    std::cout << date_buff << std::endl;
    return 0;
}
Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69
0

The type of time_t is not guaranteed by the C specification.

Unix and POSIX-compliant systems implement the time_t type as a signed integer (typically 32 or 64 bits wide) which represents the number of seconds since the start of the Unix epoch. So you may just do the following

std::time_t my_time = static_cast<std::time_t>(unixtime);

However, it is better to not to assume time to be an int and replace your time function with the appropriate time handling and return std::time_t or struct tm

HAL
  • 3,888
  • 3
  • 19
  • 28