我需要删除日期时间的时间部分,或者可能有以下格式的日期在对象形式,而不是在字符串形式。
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对象。
当前回答
创建只包含所需属性的结构体。然后使用扩展方法从DateTime实例轻松获取该结构。
public struct DateOnly
{
public int Day { get; set; }
public int Month { get; set; }
public int Year { get; set; }
}
public static class DateOnlyExtensions
{
public static DateOnly GetDateOnly(this DateTime dt)
{
return new DateOnly
{
Day = dt.Day,
Month = dt.Month,
Year = dt.Year
};
}
}
使用
DateTime dt = DateTime.Now;
DateOnly result = dt.GetDateOnly();
其他回答
试着创造你自己的结构。DateTime对象将同时具有日期和时间
这可以简单地这样做:
var dateOnly = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day)
使用ToString()方法只获取日期部分,
操作: DateTime。现在约会。ToString()“dd / MM / yyyy,
注意: “dd/ mm /yyyy”格式中的“mm”必须大写
这适用于c# 10及以上版本,现在只有DateOnly和TimeOnly格式可用。使用下面的格式,您可以从DateTime格式中提取DateOnly。
DateOnly myDateNoTime = DateOnly.FromDateTime(DateTime.Now);
您可以使用下面的简单代码。
代码:DateTime.Now.ToShortDateString ();
前任。 Console.WriteLine(DateTime.Now.ToShortDateString());