Add some specific time while using the linux command "date"
On Linux
Just use -d
(or --date
) to do some math with the dates:
date -d '+1 hour' '+%F %T'
# ^^^^^^^^^^^^
For example:
$ date '+%F %T'
2013-04-22 10:57:24
$ date -d '+1 hour' '+%F %T'
2013-04-22 11:57:24
# ^
On Mac OS
Warning, the above only works on Linux, not on Mac OS.
On Mac OS, the equivalent command is
date -v+1H
Linux and macOS in a single command
If you need to write scripts that work on both Linux servers and macOS workstations, you can silence the error of the first date
call and 'OR' it (||
) with the other. It doesn't matter which comes first.
date -u -d "+${max_age}Seconds" +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || \
date -u -v "+${max_age}S" +"%Y-%m-%dT%H:%M:%SZ"
For example, this bash function uploads a file to AWS S3 and sets a Expires:
and Cache-Control:
headers.
s3_upload_cache_control(){
local max_age_seconds="${1}" ;shift # required
local bucket_path="${1}" ;shift # required
local filename="${1}" ;shift # required
local remote_filename="/${1:-${filename}}" # optional
local fmt="+%Y-%m-%dT%H:%M:%SZ"
aws s3 cp \
"${filename}" \
"s3://${bucket_path}${remote_filename}" \
--expires "$( \
date -u -d "+${max_age_seconds}Seconds" $fmt 2>/dev/null || \
date -u -v "+${max_age_seconds}S" $fmt )" \
--cache-control max-age=$max_age,public \
--acl public-read
}
In shell script, if we need to add time then use below command and date format(PUT TIME before DATE string)
date -d"11:15:10 2017-02-05 +2 hours" +"%Y-%m-%d %H:%M:%S"
this will output
2017-02-05 13:15:10
THis does not result in correct date without UTC it does not work