user2531569
user2531569

Reputation: 619

how to set string to timestamp in unix?

I have a String variable in unix script having data like '2017010110' (format is like -- %Y%m%d%H). Please note that its not System timestamp.

Now I need to subtract -1 hour from 2017010110. Means the output should be 2017010109. I tried subtracting 1 from the variable.

But when the input is 2017010100, its obvious that I am gonna get wrong output 2017010099 (Expected output is 2016123123).

Seems like I have to set my String variable to timestamp in unix to make this subtraction of 1 hour happen.

I referred Convert date time string to UNIX timestamp in bash command but couldn't find any luck.

Could someone please help me on this?

Upvotes: 0

Views: 1065

Answers (1)

Fred
Fred

Reputation: 6995

Take a look at the code below:

#!/bin/bash
ts="2017010100"
d="[0-9]"
if
  [[ "$ts" =~ ($d$d$d$d)($d$d)($d$d)($d$d) ]]
then
  year="${BASH_REMATCH[1]}"
  month="${BASH_REMATCH[2]}"
  day="${BASH_REMATCH[3]}"
  hour="${BASH_REMATCH[4]}"
  timezone=EST
  adjusted_ts="$(date -d "$year-$month-$day $hour:00:00 $timezone - 1 hour" "+%Y%m%d%H")"
  echo "$adjusted_ts"
else
  echo "Invalid timestamp"
fi

This code splits your timestamp into individual fields, feeds GNU date with a time format it understand and removes one hour, and sets a variable to the output of this date command. The code is Bash-specific (using Bash regex matching), but it gives you a general idea.

Please note I have been forced to specify a timezone, or else (at least on my system) there is some kind of offset (probably related to UTC) that messes up the result. I have not found a way to specify some kind of "LOCAL" timezone that would avoid having to embed the system timezone in the sting. I would greatly appreciate any suggestion to improve this and make the code timezone-independent.

Upvotes: 1

Related Questions