tags:

views:

61

answers:

2

Hi,

I would like to convert the current date and time into a hex time stamp, something like:

Tue Feb 2 10:27:46 GMT 2010 converted into 0x6d054a874449e

I would like to do this from a bash script, any idea how I might do that?

Thanks J

+1  A: 
printf '0x%x' $(date +%s)
mobrule
+2  A: 

Without knowing the unit or epoch for your hex timestamp, it's hard to say for sure (and I was slightly confused by your example of "Feb 2" which is not even close to the current date!).

date +%s will convert the current date into a time_t, the number of seconds since the usual Unix epoch (which is midnight on 1st Jan 1970).

printf "0x%x" some_number will convert a value from decimal to hex.

If you need to convert to a different epoch / unit, you will need to do some calculation. You can do arithmetic in bash using $(( expression )):

$ time_t=$(date +%s)
$ echo $(($time_t * 1000))
1284505668000

If you want to convert an arbitrary date (like your "Feb 2 ..." example), rather than the current one, and are happy to assume that you have the GNU version of date, then you can use the -d option along with the +%s output format to do the conversion:

$ date -d 'Tue Feb 2 10:27:46 GMT 2010' +%s 
1265106466

An example of putting this all together:

$ time_t=$(date -d 'Tue Feb 2 10:27:46 GMT 2010' +%s)
$ time_t_ms=$(($time_t * 1000))
$ hexstamp=$(printf "0x%x" $time_t_ms)
$ echo $hexstamp
0x1268e38b4d0
Matthew Slattery