我目前正在开发一个应用程序,其功能是作为一个待办事项列表。我想知道如何从日期时间框中接收一个值,但仅使用日期的值或时间的值。我目前是这样做的。
DateTime ted = appointmentDateTimeDate.Value; //The date
DateTime at = appointmentDateTimeTime.Value; //The time
我应该用另一种方式做吗?
使用DateTime.Date
属性获取日期,使用DateTime.TimeOfDay
属性获取时间:
DateTime ted = appointmentDateTimeDate.Date; //The date
TimeSpan at = appointmentDateTimeTime.TimeOfDay; //The time
BCL并没有很好地区分日期和时间。
如果您愿意接受新的外部依赖,我想推荐我的Noda Time库,它可以让您清楚地将事物分开成LocalDate
和LocalTime
。要从日期/时间选择器执行转换,您可能会使用:
var dateAndTime = LocalDateTime.FromDateTime(appointmentDateTimeDate.Value);
LocalDate date = dateAndTime.LocalDate;
LocalTime time = dateAndTime.LocalTime;
正如其他人指出的那样,DateTime
始终具有日期和时间组件。因此,虽然可以使用两个DateTime
独立保存它们,但在大多数情况下,建议将它们一起保存在单个DateTime
实例中。
您应该确定是否真的需要将这两个值分开,或者您的应用程序是否可以将它们合并到一个属性中,这将使事情更容易。
DateTime值始终包含日期和时间,无论您是否使用它们。
您可以使用DateTime的Date属性来获取“仅日期”。它仍将具有时间值,但时间值将为午夜。您还可以使用TimeOfDay属性获取时间部分,它将是一个TimeSpan,表示自午夜以来的滴答数。
我在这里冒险猜测您正在尝试在UI中使用一个控件设置日期,另一个控件设置时间。以下是我们使用Ajax CalendarExtender附加到文本框和自定义TimePicker控件的一些代码示例。
DateTime dt;
try
{
dt = Convert.ToDateTime(txtViewDate.Text).AddHours(txtViewTime.Hour).AddMinutes(txtViewTime.Minute);
if (txtViewTime.AmPm == MKB.TimePicker.TimeSelector.AmPmSpec.PM)
{
dt = dt.AddHours(12);
}
System.Diagnostics.Debug.WriteLine(dt.ToString());
}
catch (Exception)
{
// abort processing
return;
}