문제

I did the following function:

#!/bin/bash

function calc_date(){
  odate=$1
  op=$2
  days=$3

  echo $(date "--date=$odate $op $days day" +%d%m%y) 
}

And if I call it like this:

mydate=$(calc_date '2014-02-22' '+' '2')
echo "$mydate"

Returns:

240214

Now I'm trying to get the same output calling the function by this way:

mydate=$(calc_date '220214' '+' '2')
echo "$mydate"

How could I format the date passed as parameter to the function to ddmmyy format?

도움이 되었습니까?

해결책 5

The clearest solution:

#!/bin/bash

function calc_date(){
  odate=$(date -d "$1" +%d%m%y)
  op=$2
  days=$3

  echo $(date "--date=$odate $op $days day" +%d%m%y) 
}

Example:

mydate=$(calc_date '220214' '-' '2')
echo "$mydate"

mydate=$(calc_date '220214' '+' '3')
echo "$mydate"

Result:

200214
250214

다른 팁

You are missing that date does not interpret 220214 correctly. It is interpreted as 2022-02-14 (and not as 2014-02-22).

One solution is to change or adapt your format:

$ date --date "2014-02-12 2 days ago"
Mon Feb 10 00:00:00 CET 2014

To reformat a date:

#!/bin/bash

function calc_date(){
    odate=$(echo $1 | sed -r 's/(..)(..)(..)/\3\2\1/')
    op=$2
    days=$3

    echo $(date "--date=$odate $op $days day" +%d%m%y) 
}

Here sed is simply matching 6 characters in groups of 2, then printing them back out in reverse order. So 220214 becomes 140222. This works properly with date, which recognises 6-character numerical date strings as being YYmmdd.

If your date is going backwards (i.e. your $op is negative) you will need to put the word "ago" after the "2 day"

date --date='2 day ago'

this is also you can try.

#!/bin/bash

DAYS=2

CURRENTDATE="$(date +%Y%m%d)"

echo "$CURRENTDATE"

OLDERDATE="$(date "+%Y%m%d" -d "$DAYS  days ago ")"

echo "$OLDERDATE"
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top