Frage

On my Mac OSX, my bash script has a epoch time 123439819723. I am able to convert the date to human readable format by date -r 123439819723 which gives me Fri Aug 26 09:48:43 EST 5881.

But I want the date to be in mm/ddd/yyyy:hh:mi:ss format. The date --date option doesn't work on my machine.

War es hilfreich?

Lösung

Here you go:

# date -r 123439819723 '+%m/%d/%Y:%H:%M:%S'
08/26/5881:17:48:43

In a bash script you could have something like this:

if [[ "$OSTYPE" == "linux-gnu"* ]]; then
  dayOfWeek=$(date --date @1599032939 +"%A")
  dateString=$(date --date @1599032939 +"%m/%d/%Y:%H:%M:%S")
elif [[ "$OSTYPE" == "darwin"* ]]; then
  dayOfWeek=$(date -r 1599032939 +%A)
  dateString=$(date -r 1599032939 +%m/%d/%Y:%H:%M:%S)
fi

Andere Tipps

To convert a UNIX epoch time with OS X date, use

date -j -f %s 123439819723

The -j prevents date from trying to set the system clock, and -f specifies the input format. You can add +<whatever> to set the output format, as with GNU date.

from command Shell

[aks@APC ~]$ date -r 1474588800
Fri Sep 23 05:30:00 IST 2016

[aks@APC ~]$ date -ur 1474588800
Fri Sep 23 00:00:00 UTC 2016

[aks@APC ~]$ echo "1474588800" | xargs -I {} date -jr {} -u
Fri Sep 23 00:00:00 UTC 2016

In case of Linux (with GNU coreutils 5.3+) it can be achieved using less keystrokes:

date -d @1608185188
#Wed Dec 16 22:06:28 PST 2020

On Mac one may need to install coreutils (brew install coreutils)

Combined solution to run on Mac OS.

Shell code:

T=123439819723 
D=$(date -j -f %s  $(($T/1000)) '+%m/%d/%Y:%H:%M:%S').$(($T%1000))
echo "[$T] ==> [$D]"

Output:

[123439819723] ==> [11/29/1973:11:50:19.723]

Or one line:

> echo 123439819723 | { read T; D=$(date -j -f %s  $(($T/1000)) '+%m/%d/%Y:%H:%M:%S').$(($T%1000));  echo "[$T] ==> [$D]" }
[123439819723] ==> [11/29/1973:11:50:19.723]
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top