19 Ekim 2016 Çarşamba

std::mktime metodu

Giriş
C ile şu satırı dahil ederiz.
#include <time.h>
C++ ile şu satırı dahil ederiz.
#include <ctime>
Ne İşe Yarar
Broken time yani std::tm yapısından saniye yani std::time_t yapısına geçişi sağlar. Açıklaması şöyle
This function performs the reverse translation that localtime does.
İmzası şöyle
time_t mktime (struct tm *timeptr);
Yani localtime() metodu ile elde edilen yerel saati tekrar time_t 'ye çeviriyor. Eğer tm veriyapısını elle dolduracaksak yerel saati vermemiz lazım. Şöyle yaparız. Dikkat edilmesi gereken nokta year alanı 1900'den başlayacak şekilde doldurulur. Ayrıca month alanı da 0'an başlar. Alanların değeri için struct tm yazısına bakınız.
struct tm info;

// 16.06.2014
info.tm_mday = 16;
info.tm_mon = 5;
info.tm_year = 114; // Years since 1900

// 08:00:00 Uhr
info.tm_hour = 8;
info.tm_min = 0;
info.tm_sec = 0;

// Convert to Unix timestamp
info.tm_isdst = -1;
time_t timestamp = mktime(&info);
printf("Timestamp: %i", timestamp); //1402898400 verir
UTC Saat
Bu metod gmtime() ile elde edilen yerel saati tekrar time_t 'ye çeviremez.
std::mktime and timezone info başlıklı soruda UTC saatin mktime() kullanılarak time_t veriyapısına döndürülmesi ile ilgili bir kaç nokta var.

struct tm yapısını değiştirir
Açıklaması şöyle
If the conversion is successful, the time object is modified. All fields of time are updated to fit their proper ranges. time->tm_wday and time->tm_yday are recalculated using information available in other fields.
Şöyle yaparız.
struct tm t = ...
struct tcopy = t;  // store original  to compare later
std::time_t seconds1 = std::mktime( &t);
if(t.tm_year != tcopy.tm_year  // compare with original
  || t.tm_mon != tcopy.tm_mon  
  || t.tm_mday != tcopy.tm_mday  
  || t.tm_hour != tcopy.tm_hour  
  || t.tm_min != tcopy.tm_min
  || t.tm_sec != tcopy.tm_sec
) {
  std::cout << "invalid" << std::endl;
}


Hiç yorum yok:

Yorum Gönder