Search code examples
linuxbashdate

How to get particular date of last 2nd of March based on today (bash)


The requirement is to get last 2nd of March in CI process in any year, meaning:

Today is: 23 Feb 2024 - last 2nd of March will be 02/03/2023

Today is: 23 Mar 2024 - last 2nd of March will be 02/03/2024 (current year)

How i can automate it in CI process (using date command)?


Solution

  • On Bash, if you have only POSIX or BSD date you can do:

    #!/bin/bash
    
    this_year=$(date "+%Y")
    last_year=$(( this_year-1 ))  # bash only...
    month=$(date "+%m")
    day=$(date "+%d")
    
    if [[ "${this_year}${month}${day}" > "${this_year}0302" ]]; then
        echo "${this_year}0302"
    else
        echo "${last_year}0302"
    fi
    

    This works since the format of YYYYMMDD can correctly sort strings representing a date in lexicographical order corresponding to the actual date. This is codified by the ISO 8601 standard.