Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format DateTime to local users locale in short time format using MonoTouch

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.

like image 966
Christer Nordvik Avatar asked Sep 26 '12 08:09

Christer Nordvik


1 Answers

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));
like image 200
Rolf Bjarne Kvinge Avatar answered Sep 17 '22 17:09

Rolf Bjarne Kvinge