开发者

.net DateTime formatting hide time if midnight?

I'm working on formatting datetime's to display on a graph, and its working great so far. I have the format string:

M/dd/yyyy HH:mm:ss

and it prints as I'd like it to except the following: I want to completely hide the HH:mm:ss if the time is midnight.

Is it possible to do without a custom iformat开发者_StackOverflowprovider?

Thanks!


DateTime time = DateTime.Now; 
string txt = time.ToString(time == time.Date ? "M/dd/yyyy" : "M/dd/yyyy HH:mm:ss");


DateTime time = DateTime.Now; 

string format = "";

if (time.Hour == 0) 
{
   format = "M/dd/yyyy";
} 
else 
{
   format = "M/dd/yyyy HH:mm:ss";
}


A culture-independent version of the solution proposed by @JDunkerley would be:

DateTime time = DateTime.Now;
string txt = time.ToString(time == time.Date ? "d" : "g");

More about standard date and time format strings here.


The proposed solution is not a very good one because it does not take into account user's localized time format, and simply assumes US English.

Here's how it should've been done:

public static string formatDateTimeWithTimeIfNotMidnight(DateTime dt)
{
    //RETURN:
    //      = String for 'dt' that will have time only if it's not midnight

    if (dt != dt.Date)
    {
        //Use time
        return dt.ToString();
    }
    else
    {
        //Only date
        return dt.ToShortDateString();
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜