Jan 4, 2012

Parsing User Supplied Dates and Times In Ruby


I'm in the middle of correcting some date/time handling in a Rails app. One of things that was wrong was the handling of user input date/time fields.  Obviously when users provide date/time values they're assuming we understand the information was provided from the perspective of their timezone.  Especially when we don't explicitly require them to provide timezone information.

The problem with this is that Ruby's DateTime.parse method always returns UTC based times.  You can see this clearly in the example below:
You can see the problem on the 6th line in the example above.  Even though the user input "2011/01/01T00:00" when that DateTime instance is converted to localtime the current timezone offset was subtracted.  In this case resulting in a time that's 6 hours earlier than desired.

The solution is straight forward of course. You just have to add the inverse of the users timezone offset to the value returned from DateTime.parse as demonstrated below.


On line 4 you can see it's correct even when converted from UTC to local time. 

As an alternative you could include the timezone information before parsing it but that's not always easy because you don't necessarily now the format of the user's input.


Of course all of this is generally pretty obvious but I shared just in case it can help some one less familiar with the issues.

2 comments:

Luke said...

Thanks for that. I had the same problem and this helped.

Luke said...

Thanks for that. I had the same problem and this helped.