Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify function from localtime to localtime_r #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

zondatw
Copy link

@zondatw zondatw commented Nov 6, 2021

Sometimes user want to display log which about time, but in following example, it will get wrong time, because localtime doc says:

The returned value points to an internal object whose validity or value may be altered by any subsequent call to gmtime or localtime."

, maybe change function to localtime_r is a good way.

In this example, it will get the current time, but I hope it's getting 2021/01/01 00:00:00

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "log/src/log.h"

#define DATETIME_BUF_SIZE 0xff
#define DATETIME_FORMAT "%Y/%m/%d %H:%M:%S"

int get_datetime(time_t timestamp, char* datetime) {
  struct tm *local;

  local = localtime(&timestamp);
  log_info("Current sec: %d", local->tm_sec);
  log_info("Current min: %d", local->tm_min);
  log_info("Current hour: %d", local->tm_hour);
  log_info("Current mday: %d", local->tm_mday);
  log_info("Current mon: %d", local->tm_mon + 1);
  log_info("Current year: %d", local->tm_year + 1900);
  log_info("Current wday: %d", local->tm_wday);
  log_info("Current yday: %d", local->tm_yday);

  strftime(datetime, DATETIME_BUF_SIZE, DATETIME_FORMAT, local);
  return 0;
}

int main() {
  time_t timestamp = 1609430400; // 2021/01/01 00:00:00
  char datetime[DATETIME_BUF_SIZE];

  get_datetime(timestamp, datetime);
  log_info("Display datetime: %s\n", datetime);
  return 0;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant