简体   繁体   中英

Negative value returned by time

I try to return number of second from 1970 with time function with stm32f4 card.

I have these datatype configured

RTC_HandleTypeDef RtcHandle;
RTC_DateTypeDef dateStruct;
RTC_TimeTypeDef timeStruct;

I do a call to

HAL_RTC_GetTime
HAL_RTC_GetDate

and i call this function

long SystemClock::getUnixTimestamp()
  struct tm timeinfo;

  //Setup a tm structure based on the RTC
  timeinfo.tm_wday = dateStruct.WeekDay;
  timeinfo.tm_mon = dateStruct.Month - 1;
  timeinfo.tm_mday = dateStruct.Date;
  timeinfo.tm_year = dateStruct.Year + 100;
  timeinfo.tm_hour = timeStruct.Hours;
  timeinfo.tm_min = timeStruct.Minutes;
  timeinfo.tm_sec = timeStruct.Seconds;

  time_t rawtime = mktime(&timeinfo);

  trace_printf("Current date and time are: %s\n", ctime(&rawtime));
  long x = time(&rawtime);
  trace_printf("time %lu\n", x);
  return x;
}

I see

Current date and time are: Wed Apr 29 22:46:00 2015
time 1430347560

5 second later, i do another call to HAL_RTC_GetTime, HAL_RTC_GetDate, getUnixTimestamp and i get

Current date and time are: Wed Apr 29 22:46:05 2015
time 1430347560

why time is not modified?

Using

printf("time %d\n", time(&rawtime));

to display rawtime is not appropriate. time_t is not necessarily an int .

Here's some code that I copied from http://en.cppreference.com/w/cpp/chrono/c/time to display the value returned by time :

#include <ctime>
#include <iostream>

int main()
{
    std::time_t result = std::time(nullptr);
    std::cout << std::asctime(std::localtime(&result))
              << result << " seconds since the Epoch\n";
}

From what I am reading, it seems that time() may return a negative value : What is ultimately a time_t typedef to?

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: midnight UTC of January 1, 1970 (not counting leap seconds). Some systems correctly handle negative time values, while others do not. Systems using a 32-bit time_t type are susceptible to the Year 2038 problem.

Functions in the time.h library will be able treat these negative values and translate them into actual dates. In fact, this can be proven on your computer since ctime() works fine.

In your situation, if you absolutely need the number of seconds, you'll want to convert/typecast the return value of time() into a long before printing it out.

printf("Time : %lu", (long)time(&rawtime));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM