1

The goal is a function, that delivers an int (or long) with the actual time. I therefor write the localtime into a string (as far as I understood this) and try to convert it with atoi/atol into my int/long. But somehow I don't get the expected result.

Things I've tried:

  • I switched from the initial int to long.
  • I changed the size of my string. If I resize it to 7 instead of my needed 15 bytes, it converts at least the date part of my string. But I need it all.

I've got the following code:

long generate_time()
{    
    time_t time1;
    time(&time1);

    char time_str[15];
    long act_time;

    strftime(time_str, 15, "%Y%m%d%H%M%S", localtime(&time1));
    printf("Actual time: %s\n", time_str);

    act_time = atol(time_str);
    printf("Transformed time: %d\n", act_time);

    return act_time;
}

Resulting in the response:

Actual time: 20170407091221 Transformed time: 1240669205

I hope this is easy to sort out and thank you all for your help in advance!

JeremyP
  • 84,577
  • 15
  • 123
  • 161
Mathias
  • 31
  • 1
  • 9

2 Answers2

3

You cannot use a long to store such data: max value for signed long is:

-2^31+1 to +2^31-1

or

-2,147,483,648 to 2,147,483,647

You can use unit64_t to do what you need

#include <stdint.h>

[...]

uint64_t act_time = strtoll(time_str, NULL, 10);
LPs
  • 16,045
  • 8
  • 30
  • 61
1

atol converts a string into a long which in your case probably is 32 bits and thus cannot hold the value 20170407091221. Your value 1240669205 is the lower 32 bits of 20170407091221.

You can easily check that with for example calc.exe on Windows:
20170407091221 as hex: 1258 49F3 1C15
1240669205 as hex: 49F3 1C15

Werner Henze
  • 16,404
  • 12
  • 44
  • 69
  • That's what I was afraid of. Is there any way to change the limitation? – Mathias Apr 07 '17 at 07:44
  • @MathiasWoellm compile it for 64 bit might work - it would on Mac OS. Or use a `long long` and [strtoll()](https://linux.die.net/man/3/strtoll) – JeremyP Apr 07 '17 at 08:36