How to format date time in a Windows Phone app lik

2019-09-07 17:21发布

问题:

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!