I need to get a date in a specific format but can't work out how to do it.
Here is how I'm getting the date at the moment.
date -r "$timestamp" +'%Y-%m-%dT%H:%M:%S.s'
However the issue is the milliseconds has too many digits for the format I need. I need the milliseconds to be limited to 3 digits.
Any idea how I can do such a thing?
Current Workaround
Not accurate but it works. I calculate the milliseconds afterwards and then just take the first three characters of the string. Obviously this doesn't take into account round up.
date_string_one=`date -r "$timestamp" +'%Y-%m-%dT%H:%M:%S.'`
date_string_milli=`date -r "$timestamp" +'%s'`
date_string="$date_string_one"`printf "%.3s" "$date_string_milli"`
You may simply use %3N
to truncate the nanoseconds to the 3 most significant digits:
$ date +"%Y-%m-%d %H:%M:%S,%3N"
2014-01-08 16:00:12,746
or
$ date +"%F %T,%3N"
2014-01-08 16:00:12,746
testet with »GNU bash, Version 4.2.25(1)-release (i686-pc-linux-gnu)«
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
:
date +"%F %T,%N"
2014-01-08 16:44:47,%N
Million ways to do this.. one simple way is to remove the trailing numbers...
date +'%Y-%m-%d %H:%M:%S.%N' | sed 's/[0-9][0-9][0-9][0-9][0-9][0-9]$//g'
or
date +'%Y-%m-%d %H:%M:%S.%N' | sed 's/......$//g'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With