如何获得一天的开始和结束时间 [英] How to get the start and end times of a day

查看:126
本文介绍了如何获得一天的开始和结束时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C#应用​​程序中,我传递了一个字符串变量,该字符串变量的格式为yyyymmdd-yyyymmdd,它表示起始日期和起始日期。我想分别获得这些日期的开始时间和结束时间。目前,我有下面的代码,但想知道是否还有一个更优雅的解决方案?

In my C# app, I pass a string variable that is of format yyyymmdd-yyyymmdd that represents a from and to date. I want to get the start and end times for these dates respectively. Currently I have the below code but was wondering if there was more of an elegant solution?

因此,对于pdr = 20090521-20090523,它将得到 20090521 00:00:00和 20090523 23:59:59

So for pdr = 20090521-20090523 would get "20090521 00:00:00" and "20090523 23:59:59"

private void ValidateDatePeriod(string pdr, out DateTime startDate, 
                                out DateTime endDate)
{
    string[] dates = pdr.Split('-');

    if (dates.Length != 2)
    {
        throw new Exception("Date period is of incorrect format");
    }

    if (dates[0].Length != 8 || dates[1].Length != 8)
    {
        throw new Exception("Split date periods are of incorrect format");
    }

    startDate = DateTime.ParseExact(dates[0] + " 00:00:00", 
        "yyyyMMdd HH:mm:ss", null);
    endDate = DateTime.ParseExact(dates[1] + "23:59:59", 
        "yyyyMMdd HH::mm:ss", null);
}


推荐答案

如果您只是担心.net精度...

If you are only worried about .Net precision...

startDate = DateTime.ParseExact(dates[0], "yyyyMMdd");
endDate = DateTime.ParseExact(dates[1], "yyyyMMdd").AddTicks(-1).AddDays(1);

您真的不需要在时间部分上将额外的值连接到字符串上。

You really don't need to concatenate extra values onto the string for the time portion.

作为附录,如果您使用它来查询例如数据库...

As an addendum, if you are using this for a query against, for example, a database...

startDate = DateTime.ParseExact(dates[0], "yyyyMMdd");
endDate = DateTime.ParseExact(dates[1], "yyyyMMdd").AddDays(1);

查询......

WHERE "startDate" >= @startDate AND "endDate" < @endDate

然后,注释中提到的精度问题并不重要。在这种情况下, endDate 不是范围的一部分,而是外部边界。

Then the precision issues noted in the comments won't really matter. The endDate in this case would not be part of the range, but the outside boundary.

这篇关于如何获得一天的开始和结束时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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