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