bashdatetime

Bash - Adding Minute/Hour to the date fetched from database in string format


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


Solution

  • Without 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