Wednesday, July 27, 2022

[SOLVED] How to get the current date and time in specific format in Shell

Issue

I just want to get the system current time using below format in shell

  Expected Format:
  2019-02-14T08:08:12.300Z

I tried below piece of script but It returned something different.

  CURRENTDATE=`date +"%Y-%m-%d %T"`
  echo $CURRENTDATE

Output

   2019-02-27 01:22:57

I just ran date command in my linux box and got below response back:

   -bash-3.2$ date
   Wed Feb 27 01:43:26 PST 2019

We are passing the above output as input JSON file. But this output is not accepted by our JSON. So I just want to pass the date and time format in the above specified format (Expected Format).


Solution

You may use:

dt=$(date '+%Y-%m-%dT%T.%zZ')
echo "$dt"

2019-02-27T04:35:56.-0500Z

Also note use of --iso-8601=seconds:

date --iso-8601=seconds

2019-02-27T04:37:29-05:00


Answered By - anubhava
Answer Checked By - Timothy Miller (WPSolving Admin)