我需要删除日期时间的时间部分,或者可能有以下格式的日期在对象形式,而不是在字符串形式。
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 dateAndTime = DateTime.Now;
Console.WriteLine(dateAndTime.ToString("dd/MM/yyyy")); // Will give you smth like 25/05/2011
阅读有关自定义日期和时间格式字符串的详细信息。
创建只包含所需属性的结构体。然后使用扩展方法从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();
这段代码使您可以清楚地分别编写日期和时间
string time = DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00");
string date = DateTime.Now.ToString("M-dd-yyyy");
MessageBox.Show(date + "\n" + time);
希望这能有所帮助。
static void Main(string[] args)
{
string dateStrings = "2014-09-01T03:00:00+00:00" ;
DateTime convertedDate = DateTime.Parse(dateStrings);
Console.WriteLine(" {0} ----------------- {1}",
convertedDate,DateTime.Parse(convertedDate.ToString()).ToString("dd/MM/yyyy"));
Console.Read();
}
我知道这是一个有很多答案的老帖子,但我还没有见过这种删除时间部分的方法。假设您有一个名为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作为时间部分。