问题
I have some strings in a specific date format that I'd like to work on using the GNU date command (coreutils 8.20). I can get date to output using the +FORMAT string, but not to understand strings input into it using the same string. I'm quite sure I'm missing something obvious. What gives?
teggl@mckinley { ~/scripts }$ date +%Y%m%dT%H%M%S
20131202T182052
teggl@mckinley { ~/scripts }$ date --date="20131202T182052" +%Y%m%dT%H%M%S
date: invalid date ‘20131202T182052’
Note: I'm not looking for awk-y string parsing, I need date to understand the date input into it, so it knows if it's valid (e.g. the date 20140231T120000 would be impossible).
回答1:
per the man page:
The --date=STRING is a mostly free format human readable date string such as "Sun, 29 Feb 2004 16:21:42 -0800" or "2004-02-29 16:21:42" or even "next Thursday". A date string may contain items indicating calendar date, time of day, time zone, day of week, relative time, relative date, and numbers. An empty string indicates the beginning of the day. The date string format is more complex than is easily documented here but is fully described in the info documentation.
The "T" seems to confuse it. This works:
$ date --date="2013-12-02 18:20:52" +%Y%m%dT%H%M%S
20131202T182052
The output format has nothing to do with the input format.
回答2:
If that is the input format you are stuck with, you may need to reformat it before sending it to date:
datestr=20131202T182052
datestr=$( echo $datestr | sed -e 's/T/ /' -e 's/^\([0-9][0-9][0-9][0-9]\)\([0-9][0-9]\)/\1-\2-/' -e 's/ \([0-9][0-9]\)\([0-9][0-9]\)/ \1:\2:/' )
date --date="$datestr" +%Y%m%dT%H%M%S
来源:https://stackoverflow.com/questions/20342620/gnu-date-and-custom-formats