简体   繁体   中英

Bash string to date wrong value

I have the following lines in a bash script:

TIME_START="20:00";

TIME_OLD_STRING=`date +%y%m%d`S`date --date=${TIME_START} +%H:%M`
echo ${TIME_OLD_STRING}
TIME_OLD_DATE=`date -d ${TIME_OLD_STRING} +%y%m%dS%H:%M`
echo ${TIME_OLD_DATE}

The purpose is to transform a string of the form HH:MM into a date of the form current_date HH:MM .

My problem is that for the lines above i get the following echoed output:

130820S20:00
130820S17:00

The current date is 20 August 2013, but the hour is not the expected one, therefore the conversion is wrong. I am expecting the second output to be also 130820S20:00

What have i done wrong and how do i correct it? Or at least which way do i go from here.

The second date command doesn't interpret TIME_OLD_STRING correctly. Only the date part of it was understood, so it uses current time instead.

From the date(1) 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.

If you need the same output twice (this is how it looks like in your example), just add another

echo ${TIME_OLD_STRING}

Otherwise, what exactly should the second date command do?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM