ERF
Energy Research and Forecasting: An Atmospheric Modeling Code
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
ERF_EpochTime.H
Go to the documentation of this file.
1 #ifndef ERF_EPOCH_TIME_H_
2 #define ERF_EPOCH_TIME_H_
3 
4 #include <string>
5 #include <sstream>
6 #include <iomanip>
7 #include <ctime>
8 
9 #ifdef _WIN32
10 #define timegm _mkgmtime
11 #endif
12 
13 AMREX_FORCE_INLINE
14 std::time_t getEpochTime(const std::string& dateTime, const std::string& dateTimeFormat) {
15  std::tm tmTime{};
16 
17  (void)dateTimeFormat;
18  // Manually parse the date string
19  if (sscanf(dateTime.c_str(), "%d-%d-%d_%d:%d:%dUTC",
20  &tmTime.tm_year, &tmTime.tm_mon, &tmTime.tm_mday,
21  &tmTime.tm_hour, &tmTime.tm_min, &tmTime.tm_sec) != 6) {
22  return -1; // Indicate failure if parsing fails
23  }
24 
25  // Adjust year and month for tm structure
26  tmTime.tm_year -= 1900; // tm_year is years since 1900
27  tmTime.tm_mon -= 1; // tm_mon is zero-based
28 
29  // Convert to epoch time (UTC)
30  return timegm(&tmTime);
31 }
32 
33 AMREX_FORCE_INLINE
34 std::string
35 getTimestamp (const amrex::Real epoch_real, const std::string& datetime_format)
36 {
37  auto epoch_nearest_sec = static_cast<std::time_t>(epoch_real);
38  std::tm *time_info = std::gmtime(&epoch_nearest_sec);
39 
40  char buffer[80];
41  std::strftime(buffer, sizeof(buffer), datetime_format.c_str(), time_info);
42  std::string str_nearest_sec(buffer);
43 
44  double frac_sec = epoch_real - epoch_nearest_sec;
45  snprintf(buffer, 80, "%.6f", frac_sec);
46  AMREX_ASSERT(buffer[0] == '0');
47  std::string str_frac_sec(buffer);
48 
49  return str_nearest_sec + str_frac_sec.substr(1);
50 }
51 
52 
53 #endif
AMREX_FORCE_INLINE std::time_t getEpochTime(const std::string &dateTime, const std::string &dateTimeFormat)
Definition: ERF_EpochTime.H:14
AMREX_FORCE_INLINE std::string getTimestamp(const amrex::Real epoch_real, const std::string &datetime_format)
Definition: ERF_EpochTime.H:35