C# 中批量設定物件的DateTime屬性為最小值
阿新 • • 發佈:2018-11-09
C# 的最小時間是 0001-01-01, 而資料庫的最小時間一般是要大於這個值:
Net Framewrok 中,
DateTime.MinValue => 0001/01/01 00:00:00
SqlDateTime.MinValue.Value => 1753/01/01 00:00:00
DateTime.MaxValue => 9999/12/31 23:59:59.999
SqlDateTime.MaxValue.Value => 9999/12/31 23:59:59.997
SQL Server 中,
DateTime 最小值 => 1753/01/01 00:00:00
SmallDateTime 最小值 => 1900/01/01 00:00:00
DateTime 最大值 => 9999/12/31 23:59:59.997
SmallDateTime 最大值 =>2079.6.6
DateTime2 最小值: 0001/01/01, 最大值:9999/12/31
MySQL:
所以, 最好是設定一個比較合適的最小時間, 暫且定為 1900-01-01.
一個物件可能有多個DateTime屬性, 如何快速且批量糾正其最小值呢?
using System; using System.Collections.Generic; namespace ConsoleApp2 { class Program { static void Main(string[] args) { Person person = new Person() { Name = "小明", Birthday = DateTime.Parse("2018-01-01") } ; Console.WriteLine("原來的:\r\n{0}", person); ValueUtil.FixedSmallestDateTime(person); Console.WriteLine("修改後:\r\n{0}", person); Console.Read(); } } public class Person { public string Name { get; set; } public DateTime Birthday { get; set; } public DateTime UpdateTime { get; set; } = DateTime.MinValue; public DateTime AddTime { get; set; } = DateTime.MinValue; public override string ToString() { return string.Format( @"Name: {0} Birthday: {1:yyyy-MM-dd HH:mm:ss} UpdateTime: {2:yyyy-MM-dd HH:mm:ss} AddTime: {3:yyyy-MM-dd HH:mm:ss} ", this.Name ,this.Birthday ,this.UpdateTime ,this.AddTime); } } public static class ValueUtil { public static readonly DateTime DateTimeSqlMinValue = DateTime.Parse("1900-01-01"); public static void FixedSmallestDateTime<T>(T item) { if (item == null) return; var arr = item.GetType().GetProperties(); if (arr == null || arr.Length == 0) return; foreach (var prop in arr) { if (prop.PropertyType != typeof(DateTime) || Convert.ToDateTime(prop.GetValue(item))>=DateTimeSqlMinValue) continue; prop.SetValue(item, DateTimeSqlMinValue); } } public static void FixedSmallestDateTime<T>(T item, DateTime specDateTime) { if (item == null) return; var arr = item.GetType().GetProperties(); if (arr == null || arr.Length == 0) return; foreach (var prop in arr) { if (prop.PropertyType != typeof(DateTime) || Convert.ToDateTime(prop.GetValue(item)) >= specDateTime) continue; prop.SetValue(item, specDateTime); } } } }