0

I have a requirement where I will be give the time in below format

2019-02-08T19:24:30.220Z by this I need to output number of days between the given date and present date.

given date = 2019-02-08T19:24:30.220Z present date = 2019-02-20T19:24:30.220Z

output = 12

  • What unix is it? Does that unix have GNU utilities, ksh93, zsh, perl or python? – Stéphane Chazelas Feb 20 at 11:10
  • 1
    Your clock must be off as you posted your question at 2019-02-20T11:03:04Z – Stéphane Chazelas Feb 20 at 11:20
  • I am using Mac and shell is zsh – Sugatur Deekshith S N Feb 20 at 11:59
  • I've added a zsh solution to my answer. – Stéphane Chazelas Feb 20 at 12:28
3

With ksh93 (often installed by default on commercial SysV based unices like AIX or Solaris), which also happens to be the /bin/sh of Solaris 11 and newer:

date=2019-02-08T19:24:30.220Z
export LC_ALL=C # to make sure the decimal radix is "."
then_in_seconds=$(printf '%(%s.%N)T\n' "$date")
now_in_seconds=$(printf '%(%s.%N)T\n' now)
difference_in_seconds=$((now_in_seconds - then_in_seconds))
difference_in_24h_periods=$((difference_in_seconds / 24 / 60 / 60))
echo "Result: $difference_in_24h_periods"

At 2019-02-20T11:17:30Z and a bit, that gave me:

Result: 11.6618110817684377

You can use $((f(difference_in_24h_periods))) where f is one of round, floor, ceil, nearbyint, trunc, rint, int like in C if you want the difference as an integer, or use printf format specifications to specify the number of significant digits.

With zsh:

zmodload zsh/datetime
date=2019-02-08T19:24:30.220Z
TZ=UTC0 strftime -rs then_in_seconds '%Y-%m-%dT%H:%M:%S' "${date%.*}"
then_in_seconds+=.${${date##*.}%Z}
now_in_seconds=$EPOCHREALTIME
difference_in_seconds=$((now_in_seconds - then_in_seconds))
difference_in_24h_periods=$((difference_in_seconds / 24 / 60 / 60))
echo "Result: $difference_in_24h_periods"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.