在 C# 中创建午夜日期时间的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/246225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to create a Midnight DateTime in C#
提问by endian
I need to create a midnight DateTime
我需要创建一个午夜 DateTime
I've just done this:
我刚刚做了这个:
DateTime endTime = DateTime.Now;
endTime.Subtract(endTime.TimeOfDay);
Haven't test it yet, I'm assuming it works but is there a better/cleaner way?
还没有测试它,我假设它有效,但有更好/更清洁的方法吗?
采纳答案by Marc Gravell
Just use foo.Date
, or DateTime.Today
for today's date
只需使用foo.Date
, 或DateTime.Today
为今天的日期
回答by mmiika
DateTime.Today
日期时间.今天
回答by WebDude
回答by zendar
DateTime endTime = DateTime.Now.Date;
Now endTime.TimeOfDay.ToString()
returns "00:00:00"
现在endTime.TimeOfDay.ToString()
返回"00:00:00"
回答by Aruna
You can use DateTime.Today
with exact seconds of the midnight.
您可以使用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();
This should print :
这应该打印:
Today: 11/24/2016 10:00:00 AM , Mid Night: 11/24/2016 11:59:59 PM
回答by David Petersen
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;
}
}
回答by Peter
var dateMidnight = DateTime.ParseExact(DateTime.Now.ToString("yyyyMMdd"), "yyyyMMdd", CultureInfo.InvariantCulture);