Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime parse not working as expected

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?

like image 639
Drew Avatar asked Dec 07 '10 19:12

Drew


People also ask

How does DateTime parse work?

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.

How to parse DateTime in js?

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.

How to parse date format in javascript?

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.


2 Answers

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.

like image 116
detunized Avatar answered Sep 30 '22 21:09

detunized


Use strptime instead of parse

puts DateTime.strptime(str, "%Y-%m-%d_%H-%M-%S")
like image 34
nunopolonia Avatar answered Sep 30 '22 20:09

nunopolonia