1

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.

Parzival
  • 55
  • 6
  • 1
    Yes, it's [chrono](https://en.cppreference.com/w/cpp/chrono). – Passer By Mar 17 '22 at 19:48
  • please, can you show it on example? I can't find in docs more about it... – Parzival Mar 17 '22 at 19:58
  • See https://stackoverflow.com/a/41613816/4832499. The unfortunate thing is, I don't think it can parse directly from a `string_view`. – Passer By Mar 17 '22 at 19:58
  • Note: You need C++20 or [this groovy library](https://howardhinnant.github.io/date/date.html) (that was pretty much incorporated into C++20) to get the cool date/time stuff Passer By's talking about – user4581301 Mar 17 '22 at 20:01

1 Answers1

1

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.

Parzival
  • 55
  • 6