alex
alex

Reputation: 1287

How to get seconds since unix epoch in Ada?

I feel very stupid as I don't seem to get a plain Natural number representing the seconds since the unix epoch (01/01/1970 00:00:00) in Ada. I've read the Ada.Calendar and it's subpackages up and down but don't seem to find a sensible way of achieving that, even though Ada.Calendar.Clock itself is supposed to be exactly what I want...

I am at my wits end. Any nudge in the right direction?

Upvotes: 5

Views: 2164

Answers (3)

flotto
flotto

Reputation: 561

In the GNAT implementation of Ada, there is a private package Ada.Calendar.Conversions which contains Ada <-> Unix conversions used by the children of Calendar.

Upvotes: 1

trashgod
trashgod

Reputation: 205805

Using Ada.Calendar.Formatting, construct a Time representing the epoch.

Epoch : constant Time := Formatting.Time_Of(1970, 1, 1, 0.0);

Examine the difference between Ada.Calendar.Clock and Epoch.

Put(Natural(Clock - Epoch)'Img);

Check the result against this epoch display or the Unix command date +%s.

See Rationale for Ada 2005: §7.3 Times and dates and Rationale for Ada 2012: §6.6 General miscellanea for additional details.

Upvotes: 9

OCTAGRAM
OCTAGRAM

Reputation: 706

According to POSIX standard UNIX time does not account leap seconds, while Ada.Calendar."-" handles them:

For the returned values, if Days = 0, then Seconds + Duration(Leap_Seconds) = Calendar."–" (Left, Right).

One option is to split Ada.Calendar.Time into pieces using Ada.Calendar.Formatting.Split and gather back using POSIX algorithm.

The best option option seems to be to use Ada.Calendar.Arithmetic.Difference. It returns Days, Seconds and Leap_Seconds. You can then combine Days * 86_400 + Seconds to get UNIX time, and Leap_Seconds will be explicitly thrown away as required by POSIX.

I have recently been solving this problem and posted a library into public domain.

Upvotes: 1

Related Questions