C++ mktime returning random dates

前端 未结 3 901
走了就别回头了
走了就别回头了 2020-12-21 05:55

I\'m trying to convert a date string to a time_t, but mktime() is returning seemingly random dates:

string datetime = \"2014-12-10 10:30\";
stru         


        
相关标签:
3条回答
  • 2020-12-21 06:45

    You need to properly zero-initialize all of the other fields of the struct tm instance before calling strptime(), since it doesn't necessarily initialize every field. From the strptime() POSIX specification:

    It is unspecified whether multiple calls to strptime() using the same tm structure will update the current contents of the structure or overwrite all contents of the structure. Conforming applications should make a single call to strptime() with a format and all data needed to completely specify the date and time being converted.

    For example, this should suffice:

    struct tm tmInfo = {0};
    
    0 讨论(0)
  • 2020-12-21 06:48

    The below code would do the work, if you want current system time in an format

     time_t current_time;
     struct tm *loctime;
    
     memset(buffer,0,strlen(buffer));
     current_time = time(NULL);
     loctime = localtime(&current_time);
     strftime(buffer,250,"--> %d/%m/%y  %H:%M:%S",loctime);
    
    0 讨论(0)
  • 2020-12-21 06:50

    You have to initialize the struct to 0 beforehand or also input the seconds:

    string datetime = "2014-12-10 10:30";
    struct tm tmInfo = { 0 };
    strptime(datetime.c_str(), "%Y-%m-%d %H:%M", &tmInfo);
    

    or

    string datetime = "2014-12-10 10:30:00";
    struct tm tmInfo;
    strptime(datetime.c_str(), "%Y-%m-%d %H:%M:%S", &tmInfo);
    
    0 讨论(0)
提交回复
热议问题