Shell Programming Blog Shell Programming Blog

Saturday, 29 September 2012

How to find the past and future dates using date command

abu sittik | 11:53 |


 
 
The "date" command in Linux is used to display the current date and time. But, we can also make the date command to display past and future dates based on the inputs/parameters that we pass to it. Below are some of the ways to find the future and past dates.
 
 
 
1) Normal dates:
Today
$ date +%Y-%m-%d
2012-09-29
 
After 2 days
$ date +%Y-%m-%d -d "2 day"
2012-10-01
 
Before 2 days
$ date +%Y-%m-%d -d "-2 day"
2012-09-27
 
Yesterday
$ date +%Y-%m-%d -d "yesterday"
2012-09-28
 
Tomorrow
$ date +%Y-%m-%d -d "next day"
2012-09-30
 
After 3 weeks
$ date +%Y-%m-%d -d "3 weeks"
2012-10-20
 
Before 3 weeks
$ date +%Y-%m-%d -d "-3 weeks"
2012-09-08
 
One Year 3 days after
$ date -d "1 year 3 days"
Wed Oct  2 02:24:53 CDT 2013
 
Last Sunday what was the date ?
$ date -d 'last sun'
Sun Sep 23 00:00:00 CDT 2012
 
How about coming Sunday?
$ date -d 'sun'
Sun Sep 30 00:00:00 CDT 2012
 
This year, what day does "Independence Day" fall on?
$ date --date='15 Aug' +%A
Wednesday
 
2) GMT Time?
$ date -u
Sat Sep 29 07:27:33 UTC 2012
 
3) Epoch time?
Number of seconds from 1970-01-01 UTC (epoch time,it is the number of seconds elapsed since midnight UTC of January 1, 1970, not counting leap seconds)
$ date +%s
1348903671
 
The opposite way conversion, from epoch time to date is shown below.
$ date --date '1970-01-01 UTC 1199968580 seconds'
Sat Sep 29 02:27:51 CDT 2012
 
To make the above command as a function which can be used always, you need to do the following steps.
Make the below function in ~/.bash_profile

epochtime () {
date --date '1970-01-01 UTC '$1' seconds'
}
 
So that you can use it as below in the command line or in a script.
$ epochtime 1199968580
Sat Sep 29 02:27:51 CDT 2012

0 Comments:

   

Post a Comment

Don't just read and walk away, Your Feedback Is Always Appreciated. I will try to reply to your queries as soon as time allows.

Note:
1. If your question is unrelated to this article, please use our Facebook Page.
2. Please always make use of your name in the comment box instead of anonymous so that i can respond to you through your name and don't make use of Names such as "Admin" or "ADMIN" if you want your Comment to be published.
3. Please do not spam, spam comments will be deleted immediately upon my review.

Regards,
Mohamed Abubakar Sittik A

 

Shell Programming Copyright © 2012 Shell Programming theme is Designed by Abusittik, Shell Programming