how.wtf

Step by step guide for the date in Bash

· Thomas Taylor

Unix provides a utility named date. As its name implies, it allows you to fetch your system’s date.

Display the current date

Displaying the current date is simple:

1echo $(date)

Output:

1Sat Feb 10 21:29:37 EST 2024

The system date was printed with the timezone information.

Display the current date in UTC

Similarly, we can display the current date in UTC (Coordinated Universal Time) using the -u flag:

1echo $(date -u)

Output:

1Sun Feb 11 02:31:06 UTC 2024

The datetime was printed with the UTC timezone information.

Format the current date

The default date output can easily be formatted in a bash script:

1now="$(date '+%Y-%m-%d')"
2echo $now

Output:

12024-02-10

The date manual page showcases all the formatting options available.

Getting a date from days ago

Using the -d or --date option, we can display a different date:

1now="$(date -d '2 days ago' '+%Y-%m-%d')"
2echo $now

Output:

12024-02-08

For MacOS users, use the -v option:

1now="$(date -v-2d '+%Y-%m-%d')"
2echo $now

ISO-8601 date in Bash

In 2011, the -I or --iso-8601 option was reintroduced to the date utility.

1now="$(date -Iseconds)"
2echo $now

Output:

12024-02-11T02:47:41+00:00

For MacOS users, the -I option does not exist. You must format instead:

1now="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
2echo $now

Output:

12024-02-11T02:54:53Z

Comparing two dates in Bash

Using -d to convert the dates to unix timestamp, we can compare them.

1dateOne=$(date -d 2022-02-10 +%s)
2dateTwo=$(date -d 2021-12-12 +%s)
3
4if [ $dateOne -ge $dateTwo ]; then
5    echo "woah!"
6fi

For MacOS users, the equivalent option is:

1dateOne=$(date -j -f "%F" 2022-02-10 +"%s")
2dateTwo=$(date -j -f "%F" 2021-12-12 +"%s")
3
4if [ $dateOne -ge $dateTwo ]; then
5    echo "woah!"
6fi

#bash  

Reply to this post by email ↪