Epoch in AngelScript

A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in AngelScript.

#include <chrono>
#include <iostream>
#include <ctime>

void main()
{
    // Use std::chrono::system_clock::now() to get the current time
    auto now = std::chrono::system_clock::now();
    std::cout << now.time_since_epoch().count() << std::endl;

    // Get elapsed time since the Unix epoch in seconds, milliseconds, or nanoseconds
    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
    auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
    auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count();

    std::cout << seconds << std::endl;
    std::cout << milliseconds << std::endl;
    std::cout << nanoseconds << std::endl;

    // Convert integer seconds or nanoseconds since the epoch into the corresponding time
    auto time_point = std::chrono::system_clock::from_time_t(seconds);
    std::time_t tt = std::chrono::system_clock::to_time_t(time_point);
    std::cout << std::ctime(&tt);

    auto time_point_nano = std::chrono::system_clock::time_point(std::chrono::nanoseconds(nanoseconds));
    tt = std::chrono::system_clock::to_time_t(time_point_nano);
    std::cout << std::ctime(&tt);
}

In this AngelScript code, we use the <chrono> library to work with time. The std::chrono::system_clock::now() function is used to get the current time.

We then use duration_cast to convert the time to seconds, milliseconds, and nanoseconds since the Unix epoch.

To convert integer seconds or nanoseconds back to a time point, we use std::chrono::system_clock::from_time_t() and std::chrono::system_clock::time_point() respectively.

When you run this program, you’ll see output similar to this:

1685123456789012345
1685123456
1685123456789
1685123456789012345
Fri May 26 12:34:56 2023
Fri May 26 12:34:56 2023

The exact numbers will depend on when you run the program.

Next, we’ll look at another time-related task: time parsing and formatting.