Home > Software engineering >  How to echo time in format '2022-12-08T15:25:30.165965Z' in Linux bash command?
How to echo time in format '2022-12-08T15:25:30.165965Z' in Linux bash command?

Time:12-19

Currently I am working on a bash script which has hardcoded the following date:

2022-12-08T15:25:30.165965Z

I would like to generate that date in the script and I would like it to be up to date. What I have tried so far is:

 date ' %d-%m-%Y %H:%M:%S.%M'

which outputs:

19-12-2022 12:40:13.40

I was wondering if someone knows how I could add the T and Z letters in the time?

CodePudding user response:

You may use:

date -u ' %d-%m-%YT%H:%M:%S.%NZ'

Here:

  • -u will print UTC date-time
  • T before %H will print literal T
  • %N prints nanosecond value
  • Z after %N will print literal Z

CodePudding user response:

$ date -u ' %FT%T.%6NZ'
2022-12-19T15:04:34.238733Z

You need GNU date for nanoseconds though.

CodePudding user response:

For microseconds precision, the most portable way would be to use perl:

perl -MPOSIX -MTime::HiRes=time -le '
    sprintf("%.6f",time()) =~ /([^.]*)(\..*)?/;
    print strftime("%FT%T".$2."Z",gmtime($1));
'
2022-12-19T14:26:13.467460Z
  • Related