2

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.

tuan long
  • 605
  • 1
  • 9
  • 18
  • What sort of integer? The question doesn't make sense. Do you mean you want to convert to unix time? – ormaaj Apr 08 '13 at 02:52

3 Answers3

11
date --date="Wed Mar 13 00:18:06 2013" '+%s'
date --date="2013-04-06" '+%s'

Only works for gnu date.

Brad Lanam
  • 5,192
  • 2
  • 19
  • 29
5

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
phatfingers
  • 9,770
  • 3
  • 30
  • 44
2

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')
Mihai Danila
  • 2,229
  • 1
  • 23
  • 28