Linux Script- Date Manipulations

前端 未结 5 668
[愿得一人]
[愿得一人] 2021-01-18 06:09

I will set one date variable(Say \'08-JUN-2011\') and I want to do some calculations based on that date namely,
1. Have to get the first day of the given day\'s month.

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-18 06:39

    Here's how to perform the manipulations using GNU date:

    #!/bin/sh
    
    USER_DATE=JUN-08-2011
    
    # first day of the month
    FIRST_DAY_OF_MONTH=$(date -d "$USER_DATE" +%b-01-%Y)
    
    PREVIOUS_DAY=$(date -d "$USER_DATE -1 days" +%b-%d-%Y)
    
    # last day of the month
    FIRST_DAY_NEXT_MONTH=$(date -d "$USER_DATE +1 month" +%b-01-%Y)
    LAST_DAY_OF_MONTH=$(date -d "$FIRST_DAY_NEXT_MONTH -1 day" +%b-%d-%Y)
    
    echo "User date: $USER_DATE"
    echo "1. First day of the month: $FIRST_DAY_OF_MONTH"
    echo "2. Previous day: $PREVIOUS_DAY"
    echo "3. Last day of the month: $LAST_DAY_OF_MONTH"
    

    The output is:

    User date: JUN-08-2011
    1. First day of the month: Jun-01-2011
    2. Previous day: Jun-07-2011
    3. Last day of the month: Jun-30-2011
    

提交回复
热议问题