I am fetching a date in string format from database in the bash script. The format of the date is YYYY-MM-DD HH24:MI
for instance,
date_string="2024-11-22 15:22"
when i try to add 1 minute to this, using the below command
ds=$(date -d "$date_string +1 minute" +"%Y-%m-%d %H:%M")
i get 2024-11-22 08:23
why is the hour getting changed. The timezone on the host is CST
.
I would appreciate any insights or suggestions
I am fetching a date in string format from database in the bash script. The format of the date is YYYY-MM-DD HH24:MI
for instance,
date_string="2024-11-22 15:22"
when i try to add 1 minute to this, using the below command
ds=$(date -d "$date_string +1 minute" +"%Y-%m-%d %H:%M")
i get 2024-11-22 08:23
why is the hour getting changed. The timezone on the host is CST
.
I would appreciate any insights or suggestions
Share Improve this question edited Nov 27, 2024 at 0:12 Ed Morton 205k18 gold badges87 silver badges205 bronze badges asked Nov 26, 2024 at 22:54 Praneeth GudumasuPraneeth Gudumasu 1779 bronze badges 5 |1 Answer
Reset to default 0Without knowing more about your environment, i.e. version of *nix, I tinkered around on my Windows git Bash. As to "why" it's doing it, we can only "guess" because *nix versions and flavors can vary in "subtle" ways.
On my git bash, running windows, I wrote the following script : As you can see, by adding the "today" to the ds1, it seems to work fine, so maybe try that.
#!/usr/bin/bash
date_string="2024-11-22 15:22"
echo "date_string : $date_string"
ds=$(date -d "$date_string +1 minute" +"%Y-%m-%d %H:%M")
echo "ds : $ds"
ds1=$(date -d "$date_string today +1 minute" +"%Y-%m-%d %H:%M")
echo "ds1 : $ds1 "
Outputs
$ ./test.sh
date_string : 2024-11-22 15:22
ds : 2024-11-22 09:23
ds1 : 2024-11-22 15:23
hth,
Adym
%Z
or%z
to the datetime format? – choroba Commented Nov 26, 2024 at 23:57date
and saving the result in yet another variable. You could demonstrate the problem you're asking for help with using justdate -d "2024-11-22 15:22 +1 minute" +"%Y-%m-%d %H:%M"
, no need for the additional distracting shenanigans. Always provide a minimal reproducible example, emphasis in this case on minimal. – Ed Morton Commented Nov 27, 2024 at 0:14date
interprets+1
asUTC+1
, then interprets the wordminute
to add one minute15:23
and then converts result toCST
by subtracting 7 hours, that is the difference between(UTC+1)
andCST
. For example,... +2 minutes
will result in07:23
(that's becausedate
assumes it'sUTC+2
and subtracts 8 hours). Try explicitly stating timezone:...="2024-11-22 15:22 CST"
or... CST +1 minute" + "%Y-...
. – Man made of meat Commented Nov 27, 2024 at 1:30date
version 8.30. – Cyrus Commented Nov 27, 2024 at 4:39