Given a string like '2013-04-06', I want to convert it to a integer as we can do in Java.I have no idea how to do this in bash shell.Does anybody know how to do this?Thanks for any help.
3 Answers
date --date="Wed Mar 13 00:18:06 2013" '+%s'
date --date="2013-04-06" '+%s'
Only works for gnu date.
To get seconds and nanoseconds, you could use the date command.
date -d "2013-04-06" "+%s.%N"
1365224400.000000000
You can adjust the format and truncate the output to, for example, omit the decimal and use only the first three characters of nanoseconds to provide milliseconds.
date -d "2013-04-06" "+%s%N" | cut -b1-13
1365224400000
Since there was no specific mention of interoperability with Java, you might consider simply removing the dashes and other characters from your value to obtain an integer consistent with your value.
Assuming that the leading zeroes are present where necessary (and they are in your example), this will give you numbers that honor the total order relation on dates and times, and it is arguably better than Java's rather arbitrary "number of milliseconds since 1970". Moreover, this is human readable, and it is actually a date in ISO 8601 standard form.
And, for a complete answer:
date_time="2013-04-06 00:00:01"
integer=$(echo "$date_time" | sed 's/[^0-9]//g')