Answers:
我为需要简单日期的时间创建了一个简单的Date结构,而无需担心时间部分,时区,本地vs.utc等。
Date today = Date.Today;
Date yesterday = Date.Today.AddDays(-1);
Date independenceDay = Date.Parse("2013-07-04");
independenceDay.ToLongString(); // "Thursday, July 4, 2013"
independenceDay.ToShortString(); // "7/4/2013"
independenceDay.ToString(); // "7/4/2013"
independenceDay.ToString("s"); // "2013-07-04"
int july = independenceDay.Month; // 7
不幸的是,不在.Net BCL中。日期通常表示为DateTime对象,时间设置为午夜。
如您所料,这意味着您将解决所有伴随的时区问题,即使对于Date对象,您绝对不希望进行任何时区处理。
date任何东西用于任何用途都是一个坏主意,除非您100%确信您的应用程序只能在一个时区运行。将所有内容另存为datetime可为您带来两全其美的体验,包括最关键的事情,这是一种轻松的方法,可以避免时区噩梦,如果服务器的时区配置发生了变化……并以您意想不到的方式开始写入数据。 Datetime可以将您保存在那里,date根本无法保存,并且如果您开始date在错误的时区上下文中写下内容,则将变得难以修复。
创建一个包装器类。像这样:
public class Date:IEquatable<Date>,IEquatable<DateTime>
{
public Date(DateTime date)
{
value = date.Date;
}
public bool Equals(Date other)
{
return other != null && value.Equals(other.value);
}
public bool Equals(DateTime other)
{
return value.Equals(other);
}
public override string ToString()
{
return value.ToString();
}
public static implicit operator DateTime(Date date)
{
return date.value;
}
public static explicit operator Date(DateTime dateTime)
{
return new Date(dateTime);
}
private DateTime value;
}
并公开value您想要的任何东西。
DateTimeKind.Unspecified以便在序列化时将其反序列化而不进行转换(可能会根据时区的不同而更改日期)。
DateTimeKind.Utc。请勿将其设置为,DateTimeKind.Unspecified因为这将确保它以包含的时区偏移量进行序列化/反序列化!无论时区如何,日历日期都是相同的,因此请不要让系统对其进行调整。
Date类型只是VB.NET使用的DateTime类型的别名(就像int变成Integer一样)。这两种类型都具有Date属性,该属性可将时间部分设置为00:00:00的对象返回给您。
DateTime对象具有一个属性,该属性仅返回值的日期部分。
public static void Main()
{
System.DateTime _Now = DateAndTime.Now;
Console.WriteLine("The Date and Time is " + _Now);
//will return the date and time
Console.WriteLine("The Date Only is " + _Now.Date);
//will return only the date
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
DateTime的时间设置为0:00:00
没有 Date类型。
但是你可以使用 DateTime.Date用来获取日期。
例如
DateTime date = DateTime.Now.Date;
DateTime.Now.Date与相同DateTime.Today。有一个DateTime.UtcNow将日期时间值返回为世界时(UTC),但是没有适用于Today的UTC等效方法或属性;DateTimeKind.UtcNow.Date是适当的表达。
您可以返回DateTime,其中时间部分为00:00:00,而忽略它。日期将作为时间戳整数进行处理,因此将日期与时间相结合是有意义的,因为无论如何该日期都存在于整数中。