Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Date Parts from a NSDate value

I'm using a UIDatePicker and I'm having problems with converting this data to a System.DateTime value in MonoTouch. There are problems with conversions from NSDate to DateTime, which I've mostly solved, but now I see that if you choose a date that is NOT in the same Daylight Savings Time period then you are an hour off. For example, if I pick a date in January 2010 I'll have an offset issue.

What I'd like to do is when a user selects a date/time from the UIDatePicker is to get the Year, Month, Day, Hour, and Minute values of the NSDate and just create a New System.DateTime with those values and I'll always be assured to get a date value exactly as the user see's it in the UIDatePicker.

How can I break down a NSDate value into the various date parts?

Thank you.

like image 613
Neal Avatar asked Aug 02 '10 23:08

Neal


2 Answers

An easy way to get rid of the daylight saving time problems is to set the time zone to GMT. Then the UIDatePicker will ignore daylight saving time:

    _datePicker.TimeZone = NSTimeZone.FromAbbreviation("GMT");

Implicit conversion of NSDate to and from DateTime is quite good in Monotouch, but you must be aware that NSDate is always an UTC time and DateTime is default set to DateTimeKind.Unspecified (when read from database) or DateTimeKind.Locale (when set with DateTime.Today). The best way to convert without complicated time-zone computations is to force the right DateTimeKind:

    // Set date to the date picker (_date is a DateTime with time part 0:00:00):
    _datePicker.Date = DateTime.SpecifyKind(_date, DateTimeKind.Utc);

    // Get the date from the date picker:
    _date = DateTime.SpecifyKind(_datePicker.Date, DateTimeKind.Unspecified);

This is easier and more reliable than getting the individual Day, Month and Year values.

like image 106
Marcel W Avatar answered Sep 30 '22 12:09

Marcel W


It appears this can be done using an instance of NSDateComponents. The following has been copied from Date Components and Calendar Units:

To decompose a date into constituent components, you use the NSCalendar method components:fromDate:. In addition to the date itself, you need to specify the components to be returned in the NSDateComponents object. For this, the method takes a bit mask composed of Calendar Units constants. There is no need to specify any more components than those in which you are interested. Listing 3 shows how to calculate today’s day and weekday.

Listing 3 Getting a date’s components

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]  initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];
like image 33
Jordan S. Jones Avatar answered Sep 30 '22 14:09

Jordan S. Jones