0

In my os

date
Tue 01 Nov 2022 06:58:10 PM HKT

Get unix timestamp

date +%s
1667300297

Get the utc time.

date -u
Tue 01 Nov 2022 10:58:08 AM UTC

If i assign a variable as a UTC time

x=$(date -u)

How can get the variable's timestamp then?

$x  +%s
bash: Tue: command not found
newview
  • 205

1 Answers1

1

If you want the current time as the number of seconds since the epoch:

x=$(date +%s)

With zsh after zmodload zsh/datetime, or with recent versions of bash, you can also do x=$EPOCHSECONDS.

x=$(date -u) stores something like Tue 01 Nov 2022 10:58:08 AM UTC or mar. 01 nov. 2022 12:05:48 UTC or 2022年 11月 01日 星期二 12:06:04 UTC depending on the user's locale with variation between systems as well into $x.

Getting the corresponding epoch seconds for that date is going to be difficult.

In the case of Tue 01 Nov 2022 10:58:08 AM UTC, if you have access to the GNU implementation of date, you're in luck as that's one of the date formats that it recognises with its -d option.

So:

epoch=$(date -d "$x" +%s)

Will work there. Your date command seems not to be the GNU one, but GNU date might be available as gdate or /opt/gnu/bin/date...

  • file /usr/bin/date – newview Nov 01 '22 at 23:12
  • /usr/bin/date: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=b740f054aaef6a85aff024858c914c7eae70a6a5, for GNU/Linux 3.2.0, stripped – newview Nov 01 '22 at 23:12