xref: /openbmc/bmcweb/features/redfish/src/utils/time_utils.cpp (revision 352e3b78d5e73ac5c2ee48ad4def6219360613c7)
11b8b02a4SEd Tanous #include "utils/time_utils.hpp"
21b8b02a4SEd Tanous 
31b8b02a4SEd Tanous #include "utils/extern/date.h"
41b8b02a4SEd Tanous 
51b8b02a4SEd Tanous #include <array>
61b8b02a4SEd Tanous #include <chrono>
71b8b02a4SEd Tanous #include <optional>
81b8b02a4SEd Tanous #include <sstream>
91b8b02a4SEd Tanous #include <string>
101b8b02a4SEd Tanous #include <string_view>
111b8b02a4SEd Tanous 
121b8b02a4SEd Tanous namespace redfish::time_utils
131b8b02a4SEd Tanous {
14c51afd54SEd Tanous 
151b8b02a4SEd Tanous std::optional<usSinceEpoch> dateStringToEpoch(std::string_view datetime)
161b8b02a4SEd Tanous {
17*352e3b78SHieu Huynh     for (const char* format : std::to_array(
18*352e3b78SHieu Huynh              {"%FT%T%Ez", "%FT%TZ", "%FT%T", "%Y%m%d", "%Y%m%dT%H%M%SZ"}))
191b8b02a4SEd Tanous     {
201b8b02a4SEd Tanous         // Parse using signed so we can detect negative dates
21c51afd54SEd Tanous         std::chrono::sys_time<usSinceEpoch> date;
221b8b02a4SEd Tanous         std::istringstream iss(std::string{datetime});
231b8b02a4SEd Tanous #if __cpp_lib_chrono >= 201907L
241b8b02a4SEd Tanous         namespace chrono_from_stream = std::chrono;
251b8b02a4SEd Tanous #else
261b8b02a4SEd Tanous         namespace chrono_from_stream = date;
271b8b02a4SEd Tanous #endif
281b8b02a4SEd Tanous         if (chrono_from_stream::from_stream(iss, format, date))
291b8b02a4SEd Tanous         {
301b8b02a4SEd Tanous             if (date.time_since_epoch().count() < 0)
311b8b02a4SEd Tanous             {
321b8b02a4SEd Tanous                 return std::nullopt;
331b8b02a4SEd Tanous             }
341b8b02a4SEd Tanous             if (iss.rdbuf()->in_avail() != 0)
351b8b02a4SEd Tanous             {
361b8b02a4SEd Tanous                 // More information left at end of string.
371b8b02a4SEd Tanous                 continue;
381b8b02a4SEd Tanous             }
39c51afd54SEd Tanous             return date.time_since_epoch();
401b8b02a4SEd Tanous         }
411b8b02a4SEd Tanous     }
421b8b02a4SEd Tanous     return std::nullopt;
431b8b02a4SEd Tanous }
441b8b02a4SEd Tanous } // namespace redfish::time_utils
45