6

I'm trying to format a 10-digit Unix time stamp (currently a string) using ctime.

However, ctime() expects a parameter of type time_t, not a string.

What must I do before I can use ctime? In other words, can I easily convert the string into a time_t?

jwheels
  • 517
  • 1
  • 7
  • 23
  • Use `strtoull` (check for overflows). – eq- Sep 05 '12 at 17:04
  • @eq-: The time is a signed quantity, not unsigned. Negative times are before 1970-01-01 00:00:00Z (and yes, that leaves an ambiguity between errors and one second before The Epoch). – Jonathan Leffler Sep 05 '12 at 18:04
  • @JonathanLeffler, I was very aware of that. However, speaking of "10 digit" timestamp does (or at least can be interpreted to do) restrict the range to non-negative timestamps. – eq- Sep 05 '12 at 18:08

2 Answers2

10

You're saying you have something like 1346426869 as a string and want it to be a time_t?

time_t raw_time = atoi("1346426869");
printf("current time is %s",ctime(&raw_time));

> current time is Fri Aug 31 11:27:49 2012
Mike
  • 47,263
  • 29
  • 113
  • 177
0

The time_t type is just an integer. It is the number of seconds since the Epoch. You'll need to parse the string first.

Start here:

http://www.gnu.org/software/libc/manual/html_node/General-Time-String-Parsing.html#General-Time-String-Parsing

and work your way forward from there.

Tony K.
  • 5,535
  • 23
  • 27