Parzival
Parzival

Reputation: 55

How to get timestamp from date time format in C++?

I would like to get timestamp from date time format in C++. I wrote C style solution, but this->cache_time doesn't promise \0 at the end because it is std::string_view.

std::time_t client::get_cache_time() {
            
    struct tm time;
    
    if(strptime(this->cache_time.data(), "%a, %d %b %Y %X %Z", &time) != NULL) {
        return timelocal(&time);
    }

    return 0;

}

Is there a strptime() alternative in c ++ what can work with std::string_view?

Thank you for help.

Upvotes: 1

Views: 658

Answers (1)

Parzival
Parzival

Reputation: 55

I don't know if this solution is clean and memory efficient, but it works.

std::time_t client::get_cache_time() {
            
    std::tm time;
    std::istringstream buffer(std::string(this->cache_time));

    buffer >> std::get_time(&time, "%a, %d %b %Y %X %Z");

    if(!buffer.fail()) {
        return timelocal(&time);
    }

    return 0;

}

std::string_view is nice, but not supported everywhere.

Upvotes: 1

Related Questions