Trying to format a date in bash and failing miserably

I’m new to scripting and trying to build something for some of our field techs to use regarding Apple TVs. The info I want to display is returned to me in JSON. That part I have figured out. I would like to add the last time an Apple TV checked in with our system and that particular value is returned in this format:

2022-11-17T19:41:49.166Z

We are using Macs on Monterey and I can only guarantee the built in shell scripting tools are available to me. Anyone know of a way to convert the above to a more layman friendly time in a 12 hour format?

That’s an ISO8601 date string. Assuming “shell tools” extends as far as osascript (AppleScript):

#!/bin/sh

isoDate="2022-11-17T19:41:49.123Z"

/usr/bin/osascript - "$isoDate" <<END

use framework "Foundation"

on run {isoDate}
	set fmt to current application's NSDateFormatter's alloc()'s init()
	fmt's setDateFormat:"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
	return (fmt's dateFromString:isoDate) as date as string
end run

END

Bit slow, but will give you a human-readable date string in whatever localized format their system preferences use.

(Although the mere thought of parsing JSON using *nix shell tools… ugh.)

2 Likes

Looks like that will work for me. Thank you!

And by shell tools I really should have just specified the default installation of what comes on macOS Monterey. We also have jq (which I’m using to parse the JSON) but I didn’t think that was applicable.

One final (hopefully question). How do I get the output of that script to be able to use it in a variable in the rest of my script?

I really appreciate your help.

Assuming this code is pasted into a larger shell script, backticks:

#!/bin/sh

function formatDate {
  /usr/bin/osascript - "$1" <<END

  use framework "Foundation"

  on run {isoDate}
    set fmt to current application's NSDateFormatter's alloc()'s init()
    fmt's setDateFormat:"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    return (fmt's dateFromString:isoDate) as date as string
  end run

END
}

isoDate="2022-11-17T19:41:49.123Z"

humanReadableDate=`formatDate "$isoDate"`

echo "The date is ${humanReadableDate}."
2 Likes

That’s working perfectly. Thank you so much for your help!!!