15 Eylül 2017 Cuma

std::localtime metodu

Giriş
Şu satır dahil edilir.
#include <ctime>
Bu metodlar saniyeden broken-down time'e çevirmek için kullanılır. C++ maalesef halen bu metodların yerine başka bir şey sunmuyor. Dolayısıyla bu metodlara mahkum kaldık.

Thread Safe
localtime ve gmtime thread safe değillerdir. Bu yüzden Linux'ta localtime_r, Windows'ta ise localtime_s metodlarını kullanmak gerekir. Açıklaması şöyle
If you have localtime_s or localtime_r available you should use either in preference to localtime.
localtime metodu
Kendi içindeki static bir struct tm alanı döndürür. Eğer kopyasını almak istersek  şöyle yaparız.
auto seconds = std::time (nullptr);
auto tm = *std::localtime (&seconds);
Biraz daha açık yazmak istersek şöyle yaparız.
time_t seconds = ...;
struct tm *t0 = localtime(&seconds);
struct tm t = *t0;
memcpy ile şöyle kullanırız.
struct tm epoch_time;
time_t seconds = 1441852;
memcpy(&epoch_time, localtime(&seconds), sizeof (struct tm));
localtime_r
Linux'ta kullanılır. Şöyle yaparız.
#define _GNU_SOURCE /* for tm_gmtoff and tm_zone */

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

int main(void)
{
  time_t t = time(NULL);
  struct tm lt = {0};

  localtime_r(&t, &lt);

  printf("Offset to GMT is %lds.\n", lt.tm_gmtoff);
  printf("The time zone is '%s'.\n", lt.tm_zone);

  return 0;
}
Metodun sonucunu da kullanabiliriz. Hata varsa NULL döner. Şöyle yaparız.
time_t t = time (NULL);
struct tm result;
struct tm *tm = localtime_r(&t, &result);
localtime_s
Windows'ta kullanılır. Örnek ver.

Hiç yorum yok:

Yorum Gönder