创建 NSDate Monotouch [英] Create NSDate Monotouch

查看:12
本文介绍了创建 NSDate Monotouch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将日期字符串转换为特定的 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?

推荐答案

最简单的方法是从 DateTime 开始设置.

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 与 DateTime 的显式转换非常好,但您必须意识到 NSDate 始终是 UTC 时间,并且 DateTime 默认设置为 DateTimeKind.Unspecified(从数据库读取时)或 DateTimeKind.Locale(当设置为日期时间.今天).在没有复杂时区计算的情况下进行转换的最佳方法是强制使用正确的 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);

这篇关于创建 NSDate Monotouch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆