0

I want to convert the unix timestamp returned by time() as time_t to an integer. I've been searching for a solution for 20 minutes, and decided to ask here.

Every solution I have found has not worked. When trying to cast from time_t to int, I get errors:

long int t = static_cast<long int> time(NULL);

error C2061: syntax error : identifier 'time'

error C2146: syntax error : missing '(' before identifier 'time'

I am very very new to C++. Thanks in advance.

Michael
  • 23
  • 1
  • 5
  • `time_t` is a 64bit number on most modern platforms, casting to an `int` will lose data. Also the syntax is `static_cast(time(nullptr));` – Mgetz Jan 06 '14 at 02:10
  • The error message tells you exactly what's wrong. – Lightness Races in Orbit Jan 06 '14 at 02:13
  • 2
    FWIW, [Clang gives an even more readable error](http://coliru.stacked-crooked.com/a/c040377135ca49cd), and upon fixing that, [another simple error](http://coliru.stacked-crooked.com/a/3cbfd604601847ba). There's absolutely no way to not figure it out with those. – chris Jan 06 '14 at 02:14
  • 1
    ...and don't forget to `#include ` (or `#include `, and use `std::time` instead). – Jerry Coffin Jan 06 '14 at 02:16

3 Answers3

3

time_t is already an integer, though it's deliberately chosen to be one that stores the system's full range of UNIX time, so I would recommend against this cast.

However, if you insist, you're on the right lines but just got the cast syntax wrong.

In general, statically casting e to T looks like this:

static_cast<T>(e)  // <-- parentheses!

Just as the error message told you, you are "missing '(' before identifier 'time'".

So, your expression will be:

long int t = static_cast<long int>(time(NULL));
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

Just read the errors and insert the 'missing ( before identifier time':

long int t = static_cast<long int>(time(NULL));

static_cast requires the value to be encapsulated in parentheses.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
  • Now I get this error: `error C2064: term does not evaluate to a function taking 1 arguments` – Michael Jan 06 '14 at 02:13
  • @user3163947: Please don't ask follow-up questions in comments. This is not a chatroom or discussion board. One question up there, one or more answers to _that_ question down here. – Lightness Races in Orbit Jan 06 '14 at 02:14
0

simply add parenthesis around time(NULL):

long int t = static_cast<long int>(time(NULL));
doomsdaymachine
  • 647
  • 6
  • 11