Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create NSDate Monotouch

I am trying to take a date string and turn it into a specific NSDate (eg. July 1, 1981), but I don't see and methods for setting the date. Does anyone know how to accomplish this? Perhaps convert a DateTime object to NSDate?

like image 720
Bryan Avatar asked Jan 27 '10 17:01

Bryan


1 Answers

The easiest way is to set it from DateTime.

REVISION: The NSDate conversion operators are now explicit, not implicit anymore! I updated the example below.

If you look at the NSDate prototype you will find two operators:

    public static explicit operator NSDate(DateTime dt);
    public static explicit operator DateTime(NSDate d);

These two will do the conversion for you.

Explicit conversion of NSDate to and from DateTime is quite good, 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 NSDate:
    DateTime date = DateTime.Parse("1981-07-01")
    NSDate nsDate = (NSDate)DateTime.SpecifyKind(date, DateTimeKind.Utc);

    // Get DateTime from NSDate:
    date = DateTime.SpecifyKind((DateTime)nsDate, DateTimeKind.Unspecified);
like image 55
Marcel W Avatar answered Sep 28 '22 10:09

Marcel W