开发者

DateTime format string pattern

Could someone please guide me on the correct format string to display a time in the following format?

   Original: #7/28/2011 09:00:03 AM#
   Required Format: 9am

   //BUT if the minutes part contains a value I want it to look like this

   O开发者_开发技巧riginal: #7/28/2011 09:21:03 AM#
   Required Format: 9:21am

Is there one format string I can use to accomplish this?

PS: I have tried h:mmtt but as expected that doesnt quite give me what I want


Format strings won't help. You want to conditionally format the string based on a value. You will have to check the minutes value yourself and apply the appropriate format string based on whether there are 0 minutes or not.

DateTime dateValue = DateTime.Parse("7/28/2011 09:00:03 AM");
string formattedString;
if (dateValue.Minute == 0)
    formattedString = dateValue.ToString(@"M/d/yyyy Htt");
else
    formattedString = dateValue.ToString(@"M/d/yyyy H:mmtt");


you need to write logic to stip out the 00 condition where whenever you found 00 as minutes then return only hour value else return hour and minutes values like

dtobj.Minute.Equals(00) ? dtobj.ToString("dd/MM/yy hhtt") : dtobj.ToString("dd/MM/yy hh:mmtt")


try~

string str = "7/28/2011 09:21:03 AM";
DateTime dt = DateTime.ParseExact(str, "M/dd/yyyy HH:mm:ss tt",CultureInfo.InvariantCulture);
Console.WriteLine(dt.Minute == 0 ? dt.ToString("HHtt"):dt.ToString("HH:mmtt"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜