DEV Community

Dmitry Romanoff
Dmitry Romanoff

Posted on

2

Bash script to find the difference between an epoch timestamp and the current date.

Bash script to find the difference between an epoch timestamp and the current date.

Here's an example Bash script to find the difference between an epoch timestamp and the current date:

#!/bin/bash

# Enter the epoch timestamp in seconds
epoch_timestamp=1649512800

# Get the current date in seconds since epoch
current_date=$(date +%s)

# Calculate the difference between the two timestamps
difference=$((current_date - epoch_timestamp))

# Print the difference in seconds, minutes, hours, and days
echo "Difference in seconds: $difference"
echo "Difference in minutes: $(($difference / 60))"
echo "Difference in hours: $(($difference / 3600))"
echo "Difference in days: $(($difference / 86400))"
Enter fullscreen mode Exit fullscreen mode

Replace 1649512800 with the epoch timestamp you want to compare with the current date. The script will output the difference in seconds, minutes, hours, and days between the two timestamps.

dmi@dmi-laptop:~$ cat my_script.sh 
#!/bin/bash

# Enter the epoch timestamp in seconds
epoch_timestamp=1649512800
echo "epoch_timestamp: $(date -d "@${epoch_timestamp}" "+%Y %m %d %H %M %S")"

# Get the current date in seconds since epoch
current_date=$(date +%s)
echo "current_date: $(date -d "@${current_date}" "+%Y %m %d %H %M %S")"

# Calculate the difference between the two timestamps
difference=$((current_date - epoch_timestamp))

# Print the difference in seconds, minutes, hours, and days
echo "Difference in seconds: $difference"
echo "Difference in minutes: $(($difference / 60))"
echo "Difference in hours: $(($difference / 3600))"
echo "Difference in days: $(($difference / 86400))"
Enter fullscreen mode Exit fullscreen mode

The script first finds the current epoch timestamp using the date +%s command. It then finds the difference between the two timestamps in seconds and prints it.

The script uses the date -d command to convert the epoch timestamp to the desired format.

The output will look like this:

dmi@dmi-laptop:~$ ./my_script.sh 
epoch_timestamp: 2022 04 09 17 00 00
current_date: 2023 04 10 19 23 09
Difference in seconds: 31630989
Difference in minutes: 527183
Difference in hours: 8786
Difference in days: 366
dmi@dmi-laptop:~$ 
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs