Get date details from NSDate value

I use UIDatePicker and I am having problems converting this data to System.DateTime in MonoTouch. There are problems with the conversions from NSDate to DateTime, which I mostly solved, but now I see that if you select a date that is NOT in the same daylight saving time, then you are an hour away. For example, if I select a date in January 2010, I will have a bias problem.

What I would like to do is when the user selects the date / time from the UIDatePicker to get the Year, Month, Day, Hour and Minute NSDate values ​​and just create a new System.DateTime with those and I will always be sure to get the value dates exactly as the user sees it in UIDatePicker.

How can I split the NSDate value into different parts of a date?

Thank.

+5
source share
3 answers

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

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

Converting NSDate directly to and from DateTime is not bad in Monotouch, but you should be aware that NSDate is always UTC, and DateTimeK is set to DateTimeKind.Unspecified (when reading from the database) or DateTimeKind.Locale (when with DateTime by default. Today). The best way to convert without complicated calculations in time zones 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 simpler and more reliable than getting individual Day, Month, and Year values.

+4
source

, , NSDateComponents. :

, NSCalendar : fromDate:. , , NSDateComponents . -, . , . 3 , .

3

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];
+2
public static DateTime NSDateToDateTime(MonoTouch.Foundation.NSDate date)
{
    return (new DateTime(2001,1,1,0,0,0)).AddSeconds(date.SecondsSinceReferenceDate);
}

public static MonoTouch.Foundation.NSDate DateTimeToNSDate(DateTime date)
{
    return MonoTouch.Foundation.NSDate.FromTimeIntervalSinceReferenceDate((date-(new DateTime(2001,1,1,0,0,0))).TotalSeconds);
}

, , NSDate DateTime, .Net World:), > DateTimeToNSDate NSDate

,

+1

All Articles