C# 在创建数据库记录之前更改DateTime属性的日期部分
我有一个视图模型,其中存储了C# 在创建数据库记录之前更改DateTime属性的日期部分,c#,asp.net-mvc-5,C#,Asp.net Mvc 5,我有一个视图模型,其中存储了日期时间,但在我的视图中使用JQUERY日期时间选择器,仅时间: 视图模型 [DataType(DataType.Time)] public DateTime? MondayFrom { get; set; } [DataType(DataType.Time)] public DateTime? MondayTo { get; set; } 目前,当调用Create方法时,它使用的是今天的日期加上从时间选择器中选择的时间 由于我并不特别关心日期时间的日期部分,因此我
日期时间
,但在我的视图中使用JQUERY
日期时间选择器
,仅时间:
视图模型
[DataType(DataType.Time)]
public DateTime? MondayFrom { get; set; }
[DataType(DataType.Time)]
public DateTime? MondayTo { get; set; }
目前,当调用Create方法时,它使用的是今天的日期加上从时间选择器中选择的时间
由于我并不特别关心日期时间的日期部分,因此我希望在创建记录之前,将日期、月份和年份更改为1900年1月1日或比记录编写日期更不具体的日期,这纯粹是为了避免将来出现任何混淆
我不想陷入这样做是否正确的困境
我正在努力处理DateTime中的日期部分,请参见以下内容:
public void CreateClub(Club club)
{
foreach (var item in club.MeetingDays)
{
// change Date part to 01/01/1900, leave the time as is..
}
_repository.CreateClub(club);
}
我如何才能确定项的日期部分,但不影响时间?只需使用该属性提取一天内的时间,并将其添加到所需的日期:
private static readonly DateTime BaseDate = new DateTime(1900, 1, 1);
var updatedDateTime = BaseDate + otherDateTime.TimeOfDay;
您甚至可以编写一两个扩展方法:
public static DateTime WithDate(this DateTime start, DateTime date)
{
// No need to use the Date property if you already know
// it will be midnight...
return date.Date + start.TimeOfDay;
}
public static DateTime WithFloorDate(this DateTime start)
{
return start.WithDate(FloorDate);
}
当然,我建议您使用where可以指定日期、时间和日期/时间值(分别有或没有时区或UTC offset0,但这是不同的对话。只需使用属性提取一天内的时间,并将其添加到所需的日期:
private static readonly DateTime BaseDate = new DateTime(1900, 1, 1);
var updatedDateTime = BaseDate + otherDateTime.TimeOfDay;
您甚至可以编写一两个扩展方法:
public static DateTime WithDate(this DateTime start, DateTime date)
{
// No need to use the Date property if you already know
// it will be midnight...
return date.Date + start.TimeOfDay;
}
public static DateTime WithFloorDate(this DateTime start)
{
return start.WithDate(FloorDate);
}
当然,我建议您使用where可以指定日期、时间和日期/时间值(分别有或没有时区或UTC偏移量0,但这是不同的对话。DateTime
是不可变的-您不能只更改其中的一部分。您可以提取时间并将其添加到“基准”日期:
假设club.MeetingDays
是一个列表
日期时间
是不可变的-您不能只更改其中的一部分。您可以提取时间并将其添加到“基准”日期:
假设club.MeetingDays
是一个列表
谢谢Skeety,我也会看看Noda时间。谢谢Skeety,我也会看看Noda时间。