Skip to content

Instantly share code, notes, and snippets.

@Ujang360
Last active March 8, 2022 22:46
Show Gist options
  • Save Ujang360/4a52f736b59be4724f6db4ebfeaf1413 to your computer and use it in GitHub Desktop.
Save Ujang360/4a52f736b59be4724f6db4ebfeaf1413 to your computer and use it in GitHub Desktop.
Nanoseconds & RFC3339 Timestamp C++
#include "date.h"
#include <chrono>
#include <ctime>
#include <iostream>
#include <sstream>
typedef struct _timestamp_struct {
int64_t unixtime_ns;
std::string rfc3339;
} TimestampData;
void print_timestamp(const TimestampData *timestamp) {
std::cout << "Current RFC3339 Timestamp : " << timestamp->rfc3339 << "\n";
std::cout << "Current Unixtime Nanoseconds : " << timestamp->unixtime_ns << "\n";
}
void get_current_timestamp(TimestampData *timestamp) {
using namespace std::chrono;
using namespace date;
const auto current_time = system_clock::now();
timestamp->unixtime_ns = duration_cast<std::chrono::nanoseconds>(current_time.time_since_epoch()).count();
timestamp->rfc3339 = format("%FT%TZ", time_point_cast<nanoseconds>(current_time));
}
int32_t main() {
TimestampData timestamp;
get_current_timestamp(&timestamp);
print_timestamp(&timestamp);
}
@Ujang360
Copy link
Author

Using Howard Hinnant's date.h

@Ujang360
Copy link
Author

Ujang360 commented Nov 16, 2019

❯ clang++ main.cpp -Wall -Wextra -O3 -march=native -std=gnu++17 -o get_unixtime_ns && ./get_unixtime_ns 
Current RFC3339 Timestamp    : 2019-11-16T05:10:38.742105610Z
Current Unixtime Nanoseconds : 1573881038742105610

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment