Epoch in Scilab

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 Scilab.

// Use datenum to get the current date and time
now = getdate();

// Print the current date and time
disp(now);

// Calculate seconds since Unix epoch
seconds_since_epoch = round(datenum(now) - datenum(1970, 1, 1)) * 24 * 60 * 60;
disp(seconds_since_epoch);

// Calculate milliseconds since Unix epoch
milliseconds_since_epoch = seconds_since_epoch * 1000;
disp(milliseconds_since_epoch);

// Calculate nanoseconds since Unix epoch
nanoseconds_since_epoch = seconds_since_epoch * 1e9;
disp(nanoseconds_since_epoch);

// Convert seconds since epoch back to a date
date_from_seconds = datestr(datenum(1970, 1, 1) + seconds_since_epoch / (24 * 60 * 60));
disp(date_from_seconds);

// Convert nanoseconds since epoch back to a date
date_from_nanoseconds = datestr(datenum(1970, 1, 1) + nanoseconds_since_epoch / (24 * 60 * 60 * 1e9));
disp(date_from_nanoseconds);

To run the program, save it as a .sce file and execute it in Scilab:

--> exec('epoch.sce', -1)
   31.    10.    2023.    15.    30.    45.    2.    304.    0.  

   1698765045.  

   1698765045000.  

   1.699D+18  

   31-Oct-2023 15:30:45  

   31-Oct-2023 15:30:45  

Note that Scilab doesn’t have built-in functions for Unix time, so we calculate it based on the difference between the current date and the Unix epoch (January 1, 1970). The precision might be slightly different from the original example due to the limitations of Scilab’s date and time functions.

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