I have Ruby code that looks vaguely like this.
str = 2010-12-02_12-10-26
puts str
puts DateTime.parse(str, "%Y-%m-%d_%H-%M-%S")
I expected to get the actual time from the parse. Instead, I'm getting output like this...
2010-12-02_12-10-26
2010-12-02T00:00:00+00:00
How do I get the time parsed in as well?
The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.
The parse() method takes a date string (such as "2011-10-10T14:48:00" ) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object.
parse(str) can read a date from a string. The string format should be: YYYY-MM-DDTHH:mm:ss. sssZ , where: YYYY-MM-DD – is the date: year-month-day.
This works:
str = "2010-12-02_12-10-26"
puts str
puts DateTime.strptime(str, "%Y-%m-%d_%H-%M-%S")
This example on Codepad.
According to the documentation parse
:
Create a new DateTime object by parsing from a String, without specifying the format.
And strptime
:
Create a new DateTime object by parsing from a String according to a specified format.
Use strptime instead of parse
puts DateTime.strptime(str, "%Y-%m-%d_%H-%M-%S")
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