bash date - ghdrako/doc_snipets GitHub Wiki

$ cat ./elapsed_time.sh
start=$(date +%s)
sleep 5
sleep 7
end=$(date +%s)
echo "Elapsed Time: $(($end-$start)) seconds"

$ ./elapsed_time.sh
Elapsed Time: 12 seconds
$ cat ./elapsed_time.sh
start=$(date +%s%N)
sleep 5
sleep 7
end=$(date +%s%N)
echo "Elapsed time: $(($end-$start)) ns"
echo "Elapsed time: $(($(($end-$start))/1000000)) ms"

$ ./elapsed_time.sh
Elapsed time: 12023674735 ns
Elapsed time: 12022 ms

-I[FMT], --iso-8601[=FMT]

FMT='date' for date only (the default), 'hours', 'minutes', 'seconds', or 'ns' for date and time to the indicated precision.

$ touch file-$(date -I)
file-2024-10-28
$ touch file-$(date -Iseconds)
file-2024-10-28T22:09:07+01:00
dateShort=$(date-I) #  2024-06-25
dateUTC=$(date-u) # Tue Jun 25 11:32:55 AM UTC 2024
year=$(date +%Y)  # 2024
monthNumber=$(date +%m) # 6
monthName=$(date +%B) # June
dayOfWeek=$(date +%A) #  Sunday -  %A for full weekday name, %a for abbreviated weekday name
dayOfYear=$(date +%j) # 177

Date


date +%D # 04/02/17

date +%Y-%m-%d # 2017-04-02

date +%Y-%m-%d': '%A # 2017-04-02: Sunday

dt=$(/bin/date +"%Y%m%d" -d "2 day ago")

date +%Y:%m:%d -d "yesterday"

 $(date +%Y:%m:%d -d "10 days ago") or $(date +%Y:%m:%d -d "10 day ago")
 
 date --date='-1 day'
 
 YESTERDAY=`TZ=GMT+24 date +%d-%m-%Y`;
 echo $YESTERDAY;

  • Bash 4.2 added printf %(datefmt)T
  • There are two special arguments,
    • -1, which means “now,” and
    • -2, which means “the time the shell was invoked.”
### Set a $today variable using -v
$ printf -v today '%(%F)T' '-1'
$ echo $today
2021-08-13

### Trivial logging (these are the same)
$ printf '%(%Y-%m-%d %H:%M:%S %z)T: %s\n' '-1' 'Your log message here'
$ printf '%(%F %T %z)T: %s\n' '-1' 'Your log message here'
2021-08-13 12:48:33 -0400: Your log message here
### When was 1628873101?
$ printf '%(%F %T)T = %s\n' '1628873101' 'Epoch 1628873101 to human readable'
2021-08-13 12:45:01 = Epoch 1628873101 to human readable
### show the name of the month from two months ago
$ date -d '2 months ago' '+%B'
$ date +%s 
1629582882
$ date -d @1629582882 '+%m/%d/%Y:%H:%M:%S'
08/21/2021:21:54:43
date --date="next week Fridey"
date --date="now"
date --date="tomorrow"
date --date="yesterday"
date --date="last week"
date --date="next week"
date --date="last month"
date --date="2015-09-12"
date --date="08/01/2015"
date -r start.sh  # -r  find the last modified time of the file
vi file-$(date "+%Y-%m-%d_%I:%M:%S").txt

dd abbreviates to date --date="<given_date>".

date "<some_format>" # prints the date in the specified format
  • %Y is the current year
  • %m is the current month
  • %d is today's date
  • %I is hours
  • %M is minutes
  • %S is seconds
⚠️ **GitHub.com Fallback** ⚠️