[英]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
Original: #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 PS:我已经尝试了
h:mmtt
但正如预期的那样,并没有给我我想要的东西
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.
您必须自己检查分钟值并根据是否有0分钟应用适当的格式字符串。
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");
你需要编写逻辑来规定00条件,每当你找到00作为分钟然后只返回小时值,否则返回小时和分钟值
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"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.