Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Linux date to yyyy-MM-dd'T'HH:mm:ss'Z' format

I need to parameter-ize a datetime value with an objective of passing to a constructed URI to make a Smartsheet API call to get data (i.e. sheets) changed in last 24 hours.

I want to use Linux date command as I can do something like date -d '1 day ago' %F to get the output of a day before today. How can I use the date command to convert the value to yyyy-MM-dd'T'HH:mm:ss'Z' format to get something like 2018-01-01T00:00:00-07:00?

If the value is not in this particular format, then Smartsheet API complains:

HTTP_01 - Error fetching resource. Status: 400 Reason: 
Bad Request : { "errorCode" : 1018, "message" : "The value '/home/my/path/to/param_file/Sysdate' was not valid for the parameter modifiedSince.", "refId" : "1xqawd3s94f4y" }

Thanks,

like image 343
Vlad Avatar asked Mar 09 '18 05:03

Vlad


3 Answers

To output date in ISO 8601 format, you'll probably want to use -I[FMT]/--iso-8601[=FMT] option, if your date supports it (GNU/Linux version does). The FMT is basically a resolution, and in your case you'll want to use s for seconds:

$ date -Is
2018-03-09T09:28:14+01:00

The alternative (for POSIX date, including BSD/OSX date) is to explicitly specify the format and output the time in UTC time zone (-u flag):

$ date -u +"%Y-%m-%dT%H:%M:%SZ"
2018-03-09T08:28:14Z

Note the importance of -u and the explicit Z we can append in that case. Without -u, we would need to output the exact time zone in +hh:mm format, but POSIX date provides support only for time zone name output (%Z). GNU date extends the format set with %:z which outputs the numeric time zone, but if already using GNU date, the first approach with -Is is simpler.

like image 97
randomir Avatar answered Oct 16 '22 13:10

randomir


When calling date in your shell use the following format

date +"%Y-%m-%dT%H-%M-%SZ"

2018-03-09T07-44-39Z

like image 5
Evyatar Meged Avatar answered Oct 16 '22 13:10

Evyatar Meged


To be shortest as possible :

date -u +"%FT%TZ" for UTC

date +"%FT%TZ" for locale's time

like image 4
jadjay Avatar answered Oct 16 '22 14:10

jadjay