我需要删除日期时间的时间部分,或者可能有以下格式的日期在对象形式,而不是在字符串形式。

06/26/2009 00:00:00:000

我不能使用任何字符串转换方法,因为我需要对象形式的日期。

我尝试先将DateTime转换为字符串,从它中删除特定的时间日期,但它添加了12:00:00 AM,只要我将它转换回DateTime对象。


当前回答

您可以使用下面的简单代码。

代码:DateTime.Now.ToShortDateString ();

前任。 Console.WriteLine(DateTime.Now.ToShortDateString());

其他回答

以上答案都没有解决我的winforms问题。

到达ONLY date的最简单方法是Datetime中的简单函数:

DateTime dt = DateTime.now;
String BirthDate = dt.ToShortDateString();

你将只在生日字符串中有日期。

将变量声明为字符串。

例子:

public string dateOfBirth ;

然后赋值如下:

dateOfBirth = ((DateTime)(datetimevaluefromDB)).ToShortDateString();

这种方法只得到日期而没有时间

DateTime date = DateTime.Now;
string Strdateonly = date.ToString("d");

输出= 5/16/2015

创建只包含所需属性的结构体。然后使用扩展方法从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();

只需使用一行代码:

var dateAndTime = DateTime.Now.Date;