How to format date time in a Windows Phone app like the native messaging app

这一生的挚爱 提交于 2019-12-12 04:38:34

问题


The native messaging app in Windows Phone 8 displays date time like these:

4/3, 8:31p

12/25, 10:01a

When I format date time using String.Format("{0:d} {0:t}"), I got these:

4/3/2013 8:31 PM

12/25/2012 10:01 AM

How can I make it as concise as the native messaging app?


回答1:


There's no standard date and time format string for this representation.

While you could simply use this:

string.Format("{0:M/d, h:mmt}");

... It won't help when your app is used in a culture which switches the order of day and month.

The closest solution is probably to take the format strings for your current culture and modify accordingly, i.e:

var culture = (CultureInfo)CultureInfo.CurrentUICulture.Clone();
// Make the AM/PM designators lowercase
culture.DateTimeFormat.AMDesignator = culture.DateTimeFormat.AMDesignator.ToLower();
culture.DateTimeFormat.PMDesignator = culture.DateTimeFormat.PMDesignator.ToLower();

var dDateFormatPattern = culture.DateTimeFormat.ShortDatePattern;
var tDateFormatPattern = culture.DateTimeFormat.ShortTimePattern;

var dateCompact = dDateFormatPattern.Replace("yyyy", "")
    .Replace("MM", "M").Replace("dd", "d").Replace(" ", "")
    .Trim(culture.DateTimeFormat.DateSeparator.ToArray());

var timeCompact = tDateFormatPattern
    .Replace("hh", "h").Replace("tt", "t").Replace(" ", "");

Console.WriteLine(DateTime.Now.ToString(dateCompact + " " + timeCompact, culture));

>>> 4/4 3:03p

... Alternatively, maybe you could just check the value of CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern and switch between a D/M pattern and a M/D pattern. It won't be perfect for all cultures, but at least you won't get an unpleasant surprise when you hit a culture which formats dates and times in a way you never expected!



来源:https://stackoverflow.com/questions/15802061/how-to-format-date-time-in-a-windows-phone-app-like-the-native-messaging-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!