C# 中批量设置对象的DateTime属性为最小值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yenange/article/details/83860028

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);
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/yenange/article/details/83860028
今日推荐