Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I need help to display date and time in desired format in Unix/ Linux. My desired format is: dd/mm/yyyy hh:mm:ss:ms in Unix or Linux. I got close using the following command:

echo $(date +%x_%r)

This returns:

08/20/2012_02:26:14 PM

Any suggestions?

share|improve this question
2  
Is there any reason you are using echo? It seems redundant, you can just use date directly –  lk- Aug 20 '12 at 18:42
    
I plan to stored the current time in a parameter and use it as part of a output file name. –  Hang Yu Aug 20 '12 at 18:44
4  
Why not use a ISO formatted date string? Those / is no good in filenames... (en.wikipedia.org/wiki/ISO_8601) –  Johan Aug 20 '12 at 18:55
add comment

5 Answers

up vote 4 down vote accepted
date +%x_%H:%M:%S:%N

if you need to print only two first nums as ms:

date +%x_%H:%M:%S:%N | sed 's/\(:[0-9][0-9]\)[0-9]*$/\1/'

to store it in the var:

VAR=$(date +%x_%H:%M:%S:%N | sed 's/\(:[0-9][0-9]\)[0-9]*$/\1/')
share|improve this answer
    
Thanks, that is what I want. –  Hang Yu Aug 20 '12 at 19:53
add comment

man date

date +"%d/%m/%Y_%H:%M:%S:%N"

More useful reading:
How to format date for display or to use in a shell script

share|improve this answer
    
Thanks for your reply. –  Hang Yu Aug 20 '12 at 19:55
add comment

If you want milliseconds instead of nanoseconds precision, you might use %3N instead of %N:

$ date +'%d/%m/%Y %H:%M:%S:%3N'
12/04/2014 18:36:20:659

or with your desired use of $(…):

$ echo "$(date +'%d/%m/%Y %H:%M:%S:%3N')"
12/04/2014 18:36:20:659

But be aware, that %N may not implemented depending on your target system or bash version. Tested on an embedded system »GNU bash, version 4.2.37(2)-release (arm-buildroot-linux-gnueabi)« there was no %N (neither %3N):

date +"%F %T,%N"
2014-01-08 16:44:47,%N
share|improve this answer
    
Looks that neither FreeBsd nor Mac Osx supports %N or %3N. –  Joe Apr 14 at 0:13
add comment

Something like this

date +'%d/%m/%Y_%H:%M:%S:%N'

Used %N for nanoseconds (000000000..999999999) since I did not find milliseconds right now

share|improve this answer
    
Thanks for your reply. –  Hang Yu Aug 20 '12 at 19:55
add comment

You can try:

echo `date +"%Y_%m_%d %H:%M:%S,"``date +%N/1000000|bc -l|grep -Eo "^([0-9]{0,3})"`

For some reason '`' is omitted, so put it after the echo and at the end, or simply:

date +"[%Y_%m_%d %H:%M:%S,%3N]"
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.