Mohammedz.com

For Linux and Shell scripting.


Leave a comment

How to find past/future dates?

what day it was exactly one month ago? Are you counting down the days to find it? Or searching for a calender?

You can use “date” command in such situations. See the example below:

****************************************
-bash-3.1$ date +%F
2009-06-29
-bash-3.1$ date -d”1 day ago” +%F
2009-06-28
-bash-3.1$ date -d”1 week ago” +%F
2009-06-22
-bash-3.1$ date -d”1 month ago” +%F
2009-05-29
-bash-3.1$ date -d”1 year ago” +%F
2008-06-29
-bash-3.1$
****************************************

These examples will show you how to find the future dates.
****************************************
-bash-3.1$
-bash-3.1$ date +%F
2009-06-29
-bash-3.1$ date -d”-1 day ago” +%F
2009-06-30
-bash-3.1$ date -d”-1 week ago” +%F
2009-07-06
-bash-3.1$ date -d”-1 month ago” +%F
2009-07-29
-bash-3.1$ date -d”-1 year ago” +%F
2010-06-29
-bash-3.1$
****************************************

~mohammed


Leave a comment

Linux: Timestamp conversion methods

A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred. This data is usually presented in a consistent format, allowing for easy comparison of two different records and tracking progress over time.

Unix timestamp is defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of January 1, 1970, not counting leap seconds. The Unix epoch is the time 00:00:00 UTC on January 1, 1970.

Some different ways to find timestamps:

# timestamp of a file (that means, file creation time in timestamp).
stat -c %Y filename.txt

# present date & time as timestamp.
date +%s

# convert timestamp to real time (readable format).
awk “BEGIN { print strftime(\”%c\”,$timestamp) }”

echo $timestamp|awk ‘{print strftime(“%c”,$1)}’

perl -e “print scalar(localtime($timestamp))”

perl -e “require ‘ctime.pl’; print &ctime($timestamp);”

# you can use date command if it has -d/–date option available.
date -d “1970-01-01 $timestamp sec GMT”

If these commands didn’t work when you copy&paste, you can download it from here.

~mohammed