2011-06-28 60 views

回答

66
#since this was yesterday 
date -dyesterday +%Y%m%d 

#more precise, and more recommended 
date -d'27 JUN 2011' +%Y%m%d 

#assuming this is similar to yesterdays `date` question from you 
#http://stackoverflow.com/q/6497525/638649 
date -d'last-monday' +%Y%m%d 

#going on @seth's comment you could do this 
DATE = "27 jun 2011"; date -d"$DATE" +%Y%m%d 

#or a method to read it from stdin 
read -p " Get date >> " DATE; printf " AS YYYYMMDD format >> %s" `date 
-d"$DATE" +%Y%m%d`  

#which then outputs the following: 
#Get date >> 27 june 2011 
#AS YYYYMMDD format >> 20110627 

#if you really want to use awk 
echo "27 june 2011" | awk '{print "date -d\""$1FS$2FS$3"\" +%Y%m%d"}' | bash 

#note | bash just redirects awk's output to the shell to be executed 
#FS is field separator, in this case you can use $0 to print the line 
#But this is useful if you have more than one date on a line 

More on Dates

注意到關於GNU日這隻能

我已閱讀:

的Solaris版本的日期,這是無法 支持-d可以與解決 取代sunfreeware.com版 日期

+0

我倒覺得OP是想解析輸入格式。 –

+0

有點像我有什麼,然後你也回答= P注意,你回答我的問題,因爲我編輯我的答案 – matchew

9
date -d "25 JUN 2011" +%Y%m%d 

輸出

20110625 
3

單date命令似乎運作良好:

date -d "27 JUN 2011" +%F 
+2

+1,歡迎來到stackoverflow,但%F輸出'YYYY-MM-DD'和OP是在'YYYYMMDD'後面 – matchew

6

只需使用bash:

convert_date() { 
    local months=(JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC) 
    local i 
    for ((i=0; i<11; i++)); do 
     [[ $2 = ${months[$i]} ]] && break 
    done 
    printf "%4d%02d%02d\n" $3 $((i+1)) $1 
} 

並調用它像這樣

d=$(convert_date 27 JUN 2011) 

,或者如果「老」的日期字符串被存儲在一個變量

d_old="27 JUN 2011" 
d=$(convert_date $d_old) # not quoted 
1

自2011年也許一些改變,但是這個工作對我來說:

$ date +"%Y%m%d" 
20150330 

無需爲-d到得到相同的出現結果。

+1

-d設置你想要格式化的日期。沒有它,日期格式化當前日期。 –

3

在OSX上,我使用-f指定輸入格式,-j不嘗試設置任何日期和輸出格式說明符。例如:

$ date -j -f "%m/%d/%y %H:%M:%S %p" "8/22/15 8:15:00 am" +"%m%d%y" 
082215 

你舉的例子:

$ date -j -f "%d %b %Y" "27 JUN 2011" +%Y%m%d 
20110627 
1

如果你想一個bash的功能在Mac OS X和Linux的作品都:

# 
# Convert one date format to another 
# 
# Usage: convert_date_format <input_format> <date> <output_format> 
# 
# Example: convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d' 
convert_date_format() { 
    local INPUT_FORMAT="$1" 
    local INPUT_DATE="$2" 
    local OUTPUT_FORMAT="$3" 
    local UNAME=$(uname) 

    if [[ "$UNAME" == "Darwin" ]]; then 
    # Mac OS X 
    date -j -f "$INPUT_FORMAT" "$INPUT_DATE" +"$OUTPUT_FORMAT" 
    elif [[ "$UNAME" == "Linux" ]]; then 
    # Linux 
    date -d "$INPUT_DATE" +"$OUTPUT_FORMAT" 
    else 
    # Unsupported system 
    echo "Unsupported system" 
    fi 
} 

# Example: 'Dec 10 17:30:05 2017 GMT' => '2017-12-10' 
convert_date_format '%b %d %T %Y %Z' 'Dec 10 17:30:05 2017 GMT' '%Y-%m-%d'