C#通过两个日期写时间作为字符串 [英] C# Writing Time Through Two Dates as String

查看:107
本文介绍了C#通过两个日期写时间作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个转换的开始和开始日期时间,该转换在此事件的开始和结束时记录。然后,我生成一个报告,该报告列出了有关该事件的一系列信息,包括其运行时间。我有一栏表示经过的总时间(以天为单位),并以日期表示开始和停止时间。一切都以天为单位,我不在乎小时/分钟/秒。

I have a begin and start DateTime for a conversion that gets logged at the start and end of this event. I then generate a report that lists a bunch of information about the event including its runtime. I have a column for total time elapsed (in days) and a date representation of start and stop. Everything is in days, I don't care about hours/minutes/seconds.

如果开始时间为 2010年9月29日,并且结束时间是 2010/9/31 我要打印:

If the start time is 9/29/2010 and the end time is 9/31/2010 I want to print:

9/29-31/2010

如果开始时间为 2010年9月29日,并且结束时间是 2010/2/2 ,我要打印:

If the start time is 9/29/2010 and the end time is 10/2/2010 I want to print:

9/29-10/2/2010

如果开始时间为 2010年12月29日,并且结束时间是 2011年1月2日,我要打印:

If the start time is 12/29/2010 and the end time is 1/2/2011 I want to print:

12/29/2010-1/2/2011

我知道我可以使用ToString( M / d / yyyy )的datetime方法可以打印每个日期,但我希望能以一种简单的方式以相似的格式打印两个日期。

I know I can use the ToString("M/d/yyyy") method of datetime to print each individual date, but I'm hoping for an easy way to print two dates in a similar format.

推荐答案

您的规则很容易转换为代码,无需花哨。

Your rules are pretty simple to translate to code, no need to get fancy.

static string GetDateRangeString(DateTime startDate, DateTime endDate)
{
    if (endDate.Year != startDate.Year)
    {
        return startDate.ToString("M/d/yyyy") + "-" + endDate.ToString("M/d/yyyy");
    }
    else if (endDate.Month != startDate.Month)
    {
        return startDate.ToString("M/d") + "-" + endDate.ToString("M/d/yyyy");
    }
    else
    {
        return startDate.ToString("M/d") + "-" + endDate.ToString("d/yyyy");
    }
}

Demos:

Console.WriteLine(GetDateRangeString(new DateTime(2010, 9, 29), new DateTime(2010, 9, 30)));
Console.WriteLine(GetDateRangeString(new DateTime(2010, 9, 29), new DateTime(2010, 10, 30)));
Console.WriteLine(GetDateRangeString(new DateTime(2010, 9, 29), new DateTime(2011, 1, 30)));

这篇关于C#通过两个日期写时间作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆