简体   繁体   English

C# 格式时间“On The Hour”

[英]C# format time “On The Hour”

I need to format the time from a DateTime object as a string.我需要将 DateTime 对象的时间格式化为字符串。 The catch is, if the time is "on the hour" as in 12:00AM, 8:00PM, I need to trim the zeros and display 12AM or 8PM.问题是,如果时间是“正点”,如 12:00AM、8:00PM,我需要修剪零并显示 12AM 或 8PM。

Is there an easy way to do this that I am missing?有没有一种简单的方法可以做到这一点,我错过了?

您必须自己进行检查:

dateTime.ToString(dateTime.Minute == 0 ? "Htt" : "H:mmtt");

Unless I'm missing something, you can do this:除非我遗漏了什么,否则你可以这样做:

DateTime date = DateTime.Now;
if (date.Minute == 0) {
   return date.ToString("Htt");
} else {
   return date.ToString("H:mmtt");
}

Obviously with the extra formatting wrapped around this.显然,额外的格式围绕着这个。 But that's the core of it.但这就是它的核心。

尝试:

myDateTime.ToString("htt");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM