gpt4 book ai didi

c# - 创建 NSDate Monotouch

转载 作者:可可西里 更新时间:2023-11-01 07:51:27 26 4
gpt4 key购买 nike

我正在尝试获取日期字符串并将其转换为特定的 NSDate(例如 1981 年 7 月 1 日),但我没有看到设置日期的方法。有谁知道如何做到这一点?也许将 DateTime 对象转换为 NSDate?

最佳答案

最简单的方法是从 DateTime 设置它。

修订:NSDate 转换运算符现在是显式的,不再是隐式的!我更新了下面的示例。

如果您查看 NSDate 原型(prototype),您会发现两个运算符:

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

这两个将为您进行转换。

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

关于c# - 创建 NSDate Monotouch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2148906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com