Как получить iso_date (ГГГГММДД) из time_t / timeval - PullRequest
4 голосов
/ 06 февраля 2011

Учитывая time_t как 1291121400, как мне получить дату этого дня в формате 20101130?

Ответы [ 4 ]

5 голосов
/ 06 февраля 2011

Используйте gmtime(3) или localtime(3), чтобы преобразовать его в struct tm (Или, лучше, реентерабельные версии gmtime_r или localtime_r), и затем используйте strftime(3), чтобы превратить его в строку. Например, если вы хочу вывод в UTC:

struct tm tm;
char buf[9];
gmtime_r(&my_time_t, &tm);
strftime(buf, sizeof(buf), "%Y%m%d", tm);
printf("The date is: %s\n", buf);
1 голос
/ 06 февраля 2011

У меня сработало следующее:

int iso_date_from_time_t ( const time_t & in_time_t_ ) 
{
     tm temp_this_tm_;

     { // the following to set local dst fields of struct tm ?
         time_t tvsec_ = time(NULL);
         localtime_r ( & tvsec_, & temp_this_tm_ ) ;
     }
     localtime_r ( & in_time_t, & temp_this_tm_ ) ;

     return ( ( ( ( 1900 + temp_this_tm_.tm_year ) * 100 + ( 1 + temp_this_tm_.tm_mon ) ) * 100 ) + temp_this_tm_.tm_mday ) ;
}

Спасибо за вашу помощь.

0 голосов
/ 06 февраля 2011
void function () 
{
    time_t     current_time;
    struct tm *struct_time;

    time( &current_time);

    struct_time = gmtime( &current_time);

    /* Now, you can get the ISO date by 
     * YYYY 'struct_time->tm_year+1900' 
     * MM 'struct_time->tm_mon+1'
     * DD 'struct_time->tm_mday' */
}

Пожалуйста, загляните внутрь структуры struct tm.

0 голосов
/ 06 февраля 2011

Используйте функции gmtime или localtime и strftime.

...