How to format DateTime to local users locale in sh

2019-06-22 09:53发布

问题:

I've tried multiple approaches, this is one of them:

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

The problem with this one is that .NET 3.5 returns a "." as the time seperator which is most likely a bug (since my Norwegian locale uses a colon): .NET (3.5) formats times using dots instead of colons as TimeSeparator for it-IT culture?

I also looked here: Retrieving current local time on iPhone?

But MT doesn't seem to have setTimeStyle on the NSDateFormatter?

So, anyone have any magic tricks up their sleeves?

My goal is to output:

21:00 / 9:00 PM

10:09 / 10:09 AM

like the statusbar in iPhone.

回答1:

Try this:

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

That said, the bug with dot/colon as the time separator for Norwegian locales has been fixed in Mono 2.12, so when MonoTouch switches to use Mono 2.12 instead of Mono 2.10 (hopefully early next year) you will be able to use this managed alternative too:

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


回答2:

I made a small research on mono sources and found that ShortTimePattern and TimeSeperator are not relate on each other (please Mono-guru's correct me if I'm wrong).

So, I tried to make iOS-only (not cross-platform) solution. That is is:

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

Output:

NSDate: 17:40

Please note that I'd test it with simulator and "nn-NO" (Norwegian Nynorsk (Norway)) locale.