创建的NSDate的MonoTouchNSDate、MonoTouch

2023-09-03 12:10:10 作者:佩奇

我想取一个日期字符串,并把它变成一个特定的NSDate(如1981年7月1日),但我看不出和设置日期的方法。有谁知道如何做到这一点?也许一个DateTime对象转换为NSDate的?

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?

推荐答案

最简单的方法是从日期时间设置。

The easiest way is to set it from DateTime.

修订:该的NSDate转换运营商目前正在明确,不隐了!我更新下面的例子。

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

如果你看一下NSDate的原型,你会发现两个运营商:

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.

的NSDate的显式转换和从日期时间是相当不错的,但你必须知道的NSDate始终是一个UTC时间和日期时间为默认设置为DateTimeKind.Unspecified(从数据库中读取时)或DateTimeKind.Locale(当与设置DateTime.Today)。 无需复杂的时区转换的计算最好的方式就是动用武力的权利DateTimeKind:

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);