BlandCorporation
BlandCorporation

Reputation: 1344

How can some number of seconds be added to a datetime stamp in Bash?

Let's say I have a string datetime stamp made in the following way:

datetimestamp="$(date "+%Y-%m-%dT%H%MZ" --utc)"

How could I easily add some number of seconds to this and print the result in the same form? Let's say I want to add two months (5184000 seconds).

Upvotes: 1

Views: 31

Answers (1)

Léa Gris
Léa Gris

Reputation: 19545

Very straight simple:

date '+%Y-%m-%dT%H%MZ' --utc --date 'now +5184000 seconds'

Lets test this:

date '+%Y-%m-%dT%H%MZ' --utc; date '+%Y-%m-%dT%H%MZ' --utc --date 'now +5184000 seconds'

Output:

2019-07-04T0036Z
2019-09-02T0036Z

Or just this:

date '+%Y-%m-%dT%H%MZ' --utc --date 'now +2 month'

Expanding on your question's sample code:

#!/usr/bin/env bash

sec_offset=5184000
datetimestamp="$(\
  date \
    '+%Y-%m-%dT%H%MZ' \
    --utc \
    --date "now + ${sec_offset} seconds"
)"

Upvotes: 2

Related Questions