TAGS :Viewed: 10 - Published at: a few seconds ago

[ Need to parse a string to date without padded 0's ]

I've read through a lot of examples, but the problem I'm facing is the date I'm getting doesn't have leading 0's and all the objective-c stuff I've found has them. So I need to take the date:

4/9/2012 1:30 PM

And determine if it is today. My place was to either grab today's date and compare it to the first part of that string, but as I said before I can't find anyway to make a date in objective c without leading 0's. I'm hoping to avoid parsing that string manually to add leading 0's.

Answer 1

Use an NSDateFormatter object

[dateFormatter setDateFormat:@"h:mm a"];

if you want 0's

[dateFormatter setDateFormat:@"hh:mm a"];

Answer 2

I think that using the single M option for your date format string will allow it to parse a single digit month value:

The possible date formats are specified here

Answer 3

@ynistersix answer is correct. In Data Formatting Guide, they said that NSDateFormatter follows http://unicode.org/reports/tr35/tr35-dates.html

h 1..2 11 Hour [1-12]. When used in skeleton data or in a skeleton passed in an API for flexible date pattern generation, it should match the 12-hour-cycle format preferred by the locale (h or K); it should not match a 24-hour-cycle format (H or k). Use hh for zero padding.

This is consistent with most other languages. Like .NET

"h" The hour, using a 12-hour clock from 1 to 12.

  • 2009-06-15T01:45:30 -> 1
  • 2009-06-15T13:45:30 -> 1

"hh" The hour, using a 12-hour clock from 01 to 12.

  • 2009-06-15T01:45:30 -> 01
  • 2009-06-15T13:45:30 -> 01