8

I have a problem with using strptime() function in c++.

I found a piece of code in stackoverflow like below and I want to store string time information on struct tm. Although I should get year information on my tm tm_year variable, I always get a garbage.Is there anyone to help me ? Thanks in advance.

    string  s = dtime;
    struct tm timeDate;
    memset(&timeDate,0,sizeof(struct tm));
    strptime(s.c_str(),"%Y-%m-%d %H:%M", &timeDate);
    cout<<timeDate.tm_year<<endl; // in the example below it gives me 113
    cout<<timeDate.tm_min<<endl; // it returns garbage 
**string s will be like "2013-12-04 15:03"**
BenMorel
  • 34,448
  • 50
  • 182
  • 322
caesar
  • 2,865
  • 11
  • 29
  • 36

1 Answers1

16
cout<<timeDate.tm_year<<endl; // in the example below it gives me 113

it is supposed to give you value decreased by 1900 so if it gives you 113 it means the year is 2013. Month will also be decreased by 1, i.e. if it gives you 1, it is actually February. Just add these values:

#include <iostream>
#include <sstream>
#include <ctime>

int main() {
    struct tm tm{};
    std::string s("2013-12-04 15:03");
    if (strptime(s.c_str(), "%Y-%m-%d %H:%M", &tm)) {
        int d = tm.tm_mday,
            m = tm.tm_mon + 1,
            y = tm.tm_year + 1900;
        std::cout << y << "-" << m << "-" << d << " "
                  << tm.tm_hour << ":" << tm.tm_min;
    }
}

outputs 2013-12-4 15:3

user4581301
  • 33,082
  • 7
  • 33
  • 54
LihO
  • 41,190
  • 11
  • 99
  • 167
  • Is there any way to block it ? I mean I want to get what it is given as string ? for example if s is "2017-04-15 04:15" I want to store tm_year 2017 tm_month=04 and tm_min=15 ? How could I do that ? @LihO – caesar Oct 22 '13 at 17:46
  • got it , only way is making some trick like that. Thanks a lot – caesar Oct 22 '13 at 17:50
  • 2
    you need to zero-out `struct tm tm` otherwise the result is undefined. :) – Aleksander Fular Apr 24 '18 at 08:57
  • 1
    should it be `struct tm tm {};`? – junhan Apr 09 '21 at 04:56
  • @junhan The man page for `strptime()` shows an example that initializes the structure with `memset(&tm, 0, sizeof (struct tm));`. – Pulseczar Sep 13 '22 at 16:18
  • @Pulseczar No need for `memset` here. With junhan's suggestion the structure is immediately [zero initialized](https://en.cppreference.com/w/cpp/language/zero_initialization) with the compiler generating the code. – user4581301 Sep 13 '22 at 21:06