如何使用MonoTouch将DateTime格式化为本地用户区域设置的短时间格式

5

我尝试过多种方法,这是其中之一:

System.Globalization.DateTimeFormatInfo format = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;      
return dt.Value.ToString (format.ShortTimePattern);

这个问题在于,.NET 3.5将"."作为时间分隔符返回,这很可能是一个bug(因为我的挪威语环境使用冒号): .NET(3.5)格式化时间时使用点而不是冒号作为it-IT文化的TimeSeparator? 我也在这里找过: Retrieving current local time on iPhone? 但MT似乎没有NSDateFormatter的setTimeStyle?
那么,有人有什么魔法技巧可以分享吗?
我的目标是输出: 21:00 / 下午9:00 10:09 / 上午10:09 就像iPhone状态栏一样。
2个回答

6

试试这个:

var formatter = new NSDateFormatter ();
formatter.TimeStyle = NSDateFormatterStyle.Short;
Console.WriteLine (formatter.ToString (DateTime.Now));

话虽如此,对于使用挪威语区域设置时点号/冒号作为时间分隔符的错误已在Mono 2.12中得到修复。因此,当MonoTouch在明年初切换到使用Mono 2.12而不是Mono 2.10后,您也将能够使用这个托管替代方案:

Console.WriteLine (DateTime.Now.ToString (new CultureInfo ("nb-NO").DateTimeFormat.ShortTimePattern));

非常好!我总是忘记许多 Obj-C 方法在 MT 中是属性 :-) - Christer Nordvik

1

我对Mono源进行了小型研究,发现ShortTimePattern和TimeSeperator 并不相关(如果我错了,请Mono大师们纠正我)。

因此,我尝试制作仅适用于iOS(非跨平台)的解决方案。具体如下:

using MonoTouch.Foundation;
    ...
    public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();

        var d = DateTime.Now;
        Console.WriteLine("NSDate: " + GetCorrectTime(d));
    }
    ...
        // iOS-only (not cross-platform)
    public string GetCorrectTime (DateTime d)
    {
        var nsdate = DateTimeToNSDate(d);
        var nsdateformatter = new .NSDateFormatter();
        nsdateformatter.DateStyle = NSDateFormatterStyle.None;
        nsdateformatter.TimeStyle = NSDateFormatterStyle.Short;
        return nsdateformatter.ToString(nsdate);
    }
    ...
        // DateTime to NSDate was taken from [that post][2]
    public static NSDate DateTimeToNSDate(DateTime date)
    {
        return NSDate.FromTimeIntervalSinceReferenceDate((date-(new DateTime(2001,1,1,0,0,0))).TotalSeconds);
    }

输出:

NSDate: 17:40

请注意,我已经使用模拟器和“nn-NO”(挪威尼诺斯克语(挪威))区域设置进行了测试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接