Epoch in Modelica
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 Modelica.
model Epoch
import Modelica.Utilities.System;
import Modelica.Utilities.Streams;
equation
when initial() then
// Get the current time in seconds since the epoch
Real currentTime = System.getTime();
// Print the current time
Streams.print("Current time: " + String(currentTime));
// Calculate milliseconds and nanoseconds
Real milliseconds = currentTime * 1000;
Real nanoseconds = currentTime * 1e9;
Streams.print("Seconds since epoch: " + String(currentTime));
Streams.print("Milliseconds since epoch: " + String(milliseconds));
Streams.print("Nanoseconds since epoch: " + String(nanoseconds));
// Convert back to time
Real convertedTime = System.getTime();
Streams.print("Converted time: " + String(convertedTime));
end when;
end Epoch;
In Modelica, we don’t have direct equivalents for all the time-related functions available in some other languages. However, we can use the System.getTime()
function to get the current time in seconds since the epoch.
To run this model:
$ openmodelica Epoch.mo
Current time: 1679012345.678
Seconds since epoch: 1679012345.678
Milliseconds since epoch: 1679012345678.0
Nanoseconds since epoch: 1.679012345678e+18
Converted time: 1679012345.678
Note that Modelica doesn’t provide built-in functions for millisecond or nanosecond precision, so we’re calculating these values manually. Also, there’s no direct equivalent to converting integer seconds or nanoseconds back to a time object, so we’re just demonstrating getting the current time again.
Next, we’ll look at another time-related task: time formatting and parsing, which may require additional libraries or external functions in Modelica.