我需要删除日期时间的时间部分,或者可能有以下格式的日期在对象形式,而不是在字符串形式。
06/26/2009 00:00:00:000
我不能使用任何字符串转换方法,因为我需要对象形式的日期。
我尝试先将DateTime转换为字符串,从它中删除特定的时间日期,但它添加了12:00:00 AM,只要我将它转换回DateTime对象。
我需要删除日期时间的时间部分,或者可能有以下格式的日期在对象形式,而不是在字符串形式。
06/26/2009 00:00:00:000
我不能使用任何字符串转换方法,因为我需要对象形式的日期。
我尝试先将DateTime转换为字符串,从它中删除特定的时间日期,但它添加了12:00:00 AM,只要我将它转换回DateTime对象。
当前回答
你不能。. net中的DateTime总是有一个时间,默认为00:00:00:000。DateTime的Date属性也是DateTime(!),因此时间默认为00:00:00:000。
这是. net框架的不足之处,可以认为。net中的DateTime违反了单一责任原则。
其他回答
我认为你会这样:DateTime onlyDate = DateTime. today . date; 或者,这是相同的DateTime onlyDate = yourDateTime.Date; 所以使用属性Date。
DateTime。日期
var newDate = DateTime.Now; //newDate.Date property is date portion of DateTime
string dt = myCalender.SelectedDate.ToString();
string date = dt.Remove(10);
displayDate.Content = date;
如果你从日历上取日期,我们也会得到时间。这不是一直都需要的。使用它,我们可以从日期中删除时间。
下面是另一个使用String的方法。格式
DateTime todaysDate = DateTime.UtcNow;
string dateString = String.Format("{0:dd/MM/yyyy}", todaysDate);
Console.WriteLine("Date with Time: "+ todaysDate.ToString());
Console.WriteLine("Date Only : " + dateString);
输出:
Date with Time: 9/4/2016 11:42:16 AM
Date Only : 04/09/2016
如果日期时间存储在数据库中,这也适用。
有关更多日期和时间格式,请检查这些链接:
参考1
参考2
希望有帮助。
我知道这是一个有很多答案的老帖子,但我还没有见过这种删除时间部分的方法。假设您有一个名为myDate的DateTime变量,其中日期和时间部分。你可以从它创建一个新的DateTime对象,没有时间部分,使用这个构造函数:
public DateTime(int year, int month, int day);
是这样的:
myDate = new DateTime(myDate.Year, myDate.Month, myDate.Day);
通过这种方式,您可以基于旧的DateTime对象创建一个新的DateTime对象,其中00:00:00作为时间部分。