用C#创建Midnight DateTime的最佳方式



我需要创建一个午夜DateTime

我刚刚做了这个:

DateTime endTime = DateTime.Now;
endTime.Subtract(endTime.TimeOfDay);

还没有测试过,我想它是有效的,但有更好/更干净的方法吗?

只需将foo.DateDateTime.Today用于今天的日期

DateTime endTime = DateTime.Now.Date;

现在endTime.TimeOfDay.ToString()返回"00:00:00"

DateTime.NowAddDays(1)Date

DateTime.Today

您可以使用DateTime.Today和精确的午夜秒数。

    DateTime today = DateTime.Today;
    DateTime mid = today.AddDays(1).AddSeconds(-1);
    Console.WriteLine(string.Format("Today: {0} , Mid Night: {1}", today.ToString(), mid.ToString()));
    Console.ReadLine();

这应该打印:

Today: 11/24/2016 10:00:00 AM , Mid Night: 11/24/2016 11:59:59 PM
var dateMidnight = DateTime.ParseExact(DateTime.Now.ToString("yyyyMMdd"), "yyyyMMdd", CultureInfo.InvariantCulture);
    private bool IsServiceDatabaseProcessReadyToStart()
    {
        bool isGoodParms = true;
        DateTime currentTime = DateTime.Now;
        //24 Hour Clock
        string[] timeSpan = currentTime.ToString("HH:mm:ss").Split(':');
        //Default to Noon
        int hr = 12;
        int mn = 0;
        int sc = 0;
        if (!string.IsNullOrEmpty(timeSpan[0]))
        {
            hr = Convert.ToInt32(timeSpan[0]);
        }
        else
        {
            isGoodParms = false;
        }
        if (!string.IsNullOrEmpty(timeSpan[1]))
        {
            mn = Convert.ToInt32(timeSpan[1]);
        }
        else
        {
            isGoodParms = false;
        }
        if (!string.IsNullOrEmpty(timeSpan[2]))
        {
            sc = Convert.ToInt32(timeSpan[2]);
        }
        else
        {
            isGoodParms = false;
        }
        if (isGoodParms == true )
        {
            TimeSpan currentTimeSpan = new TimeSpan(hr, mn, sc);
            TimeSpan minTimeSpan = new TimeSpan(0, 0, 0);
            TimeSpan maxTimeSpan = new TimeSpan(0, 04, 59);
            if (currentTimeSpan >= minTimeSpan && currentTimeSpan <= maxTimeSpan)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

相关内容

  • 没有找到相关文章

最新更新