I am using UIDatePicker in my app and when i take the date that was chosen with:
NSDate *date = picker.date;
picker.date
returned the day before the date that I chose.
any idea why it happens?
I am using UIDatePicker in my app and when i take the date that was chosen with:
NSDate *date = picker.date;
picker.date
returned the day before the date that I chose.
any idea why it happens?
give this a try worked for me
//i'm outputting mine in a label you can use anything you like
Just add one line of code
0 is for GMT 00 . Add according to your time zone.
Did you check the timezone?
When you print an
NSDate
it will use GMT as it timezone.If you set the system timezone to the NSDateFormatter you might get an other date, because it will take the timezone and calculate the time accordingly.
Add this code and see if the output is correct:
UIDatePicker
will be displaying dates and times in your local timezone. However,NSDate
does not have any concept of a timezone as it stores an absolute number of seconds since a reference date. WhenNSLogging
a date, it shows the date and time in GMT. I expect if you work out your local timezone difference from GMT, you will see that it is the correct date.Try creating an NSDateFormatter or NSCalendar with the appropriate locale and pass the date through that.
For further reading on this common topic, see this site written by another SO contributor.
Remember to create the NSDate and then output it with a valid timezone and calendar!
NSDate only represents an absolute point in time. It has no concept of timezone (NY, Barcelona, ...) or calendar (Gregorian, Hebrew, ...).
UIDatePicker returns by default a NSDate with the system NSCalendar and NSTimeZone, but when you try to print it later, you do not format the output. You may have there the mismatch.
So 1st you need to setup the UIDatePicker correctly and 2nd transform the output with the NSDateFormatter so it knows the Calendar and the TimeZone being used.
An example code with the init of the UIDatePicker and then printing the result:
Check the answer I did for another very similar question: