문제

I have time format like [%Y-%m-%d %H:%M:%S] and time stamp like [2009/05/11 07:30:00]. What I need is How to compare these two values. Possible is that time stamp is not similar like time format, for example [%Y-%m%d %H:%M]. This is wrong. Some ideas?

도움이 되었습니까?

해결책 2

To verify that a date string is in a specific format, you can coerce the date into the format you want and verify that the string is the same as you started with:

$ format='%Y/%m/%d %H:%M:%S'
$ invalid_date='2009/05/11 07:30'
$ [ "$(date --date="$invalid_date" +"$format")" = "$invalid_date" ]
$ echo "$?"
1
$ valid_date='2009/05/11 07:30:00'
$ [ "$(date --date="$valid_date" +"$format")" = "$valid_date" ]
$ echo "$?"
0

This will only work for date strings which are date compatible (you can't specify the input formatting directly in date).

다른 팁

If the dates are not necessarily in the same format, one simple way is to convert them to Unix timestamps:

$ date --date="2009/05/11 07:30:00" +%s
1242023400
$ date --date="2009/05/11 07:30" +%s
1242023400

This will give you an integer value which you can easily compare using:

if [ "$(date --date="$my_date" +%s)" -gt "$(date --date="$my_other_date" +%s)" ]

date understands many common date formats without having to munge the input first.

If the dates are in the same format, and that format is 4-digit year followed by month, date, hour, minute, and second, but some are truncated at the end, you can fill in the suffix and compare those dates as strings:

$ rpad_date() {
    case ${#1} in
        4)
            format='%s/01/01 00:00:00'
            ;;
        7)
            format='%s/01 00:00:00'
            ;;
        10)
            format='%s 00:00:00'
            ;;
        13)
            format='%s:00:00'
            ;;
        16)
            format='%s:00'
            ;;
        19)
            format='%s'
            ;;
        *)
            echo "Unknown format: $1" >&2
            return 1
     esac
     printf "$format" "$1"
}
$ rpad_date "2004"
2004/01/01 00:00:00
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top