How to display modification time of a file?

Don't use ls, this is a job for stat:

stat -c '%y' filename

-c lets us to get specific output, here %y will get us the last modified time of the file in human readable format. To get time in seconds since Epoch use %Y:

stat -c '%Y' filename

If you want the file name too, use %n:

stat -c '%y : %n' filename
stat -c '%Y : %n' filename

Set the format specifiers to suit your need. Check man stat.

Example:

% stat -c '%y' foobar.txt
2016-07-26 12:15:16.897284828 +0600

% stat -c '%Y' foobar.txt
1469513716

% stat -c '%y : %n' foobar.txt
2016-07-26 12:15:16.897284828 +0600 : foobar.txt    

% stat -c '%Y : %n' foobar.txt
1469513716 : foobar.txt

If you want the output like Tue Jul 26 15:20:59 BST 2016, use the Epoch time as input to date:

% date -d "@$(stat -c '%Y' a.out)" '+%a %b %d %T %Z %Y'
Tue Jul 26 12:15:21 BDT 2016

% date -d "@$(stat -c '%Y' a.out)" '+%c'               
Tue 26 Jul 2016 12:15:21 PM BDT

% date -d "@$(stat -c '%Y' a.out)"
Tue Jul 26 12:15:21 BDT 2016

Check date's format specifiers to meet your need. See man date too.


I tried

ls -l $filename | cut -d ' ' -f '6-8'

but if the date is less than 10 it misses the time. This because of the extra space before the date if less than 10. Try this:

filename="test.txt"
ls -l $filename | awk -F ' ' '{print $6" "$7" "$8}'

The awk command prints the fields separated by all spaces (-F ' '). Hope it works. I know this doesn't answer the original question but just a clarification on the ls command for just date and time. When you Google "ubuntu get date and time of file" it lists this question at the top, which is what I was looking for, since I don't need the year also. For year, date and time, you could try one of the commands below. %m prints month number. %b prints month abbreviation: Drop the %H:%M if you don't need the hour and minute. %-d doesn't print leading zero for the day of the month.

date -r $filename +"%Y %m %-d %H:%M"
date -r $filename +"%y %m %-d %H:%M"
date -r $filename +"%Y %b %-d %H:%M"
date -r $filename +"%y %b %-d %H:%M"