How to remove time portion of date in C# in DateTime object only?

后端 未结 30 3735
醉话见心
醉话见心 2020-11-22 09:08

I need to remove time portion of date time or probably have the date in following format in object form not in the form of string.

         


        
30条回答
  •  無奈伤痛
    2020-11-22 09:32

    Create a struct that holds only the properties you want. Then an extension method to easily get that struct from an instance of DateTime.

    public struct DateOnly
    {
        public int Day { get; set; }
        public int Month { get; set; }
        public int Year { get; set; }
    }
    
    public static class DateOnlyExtensions
    {
        public static DateOnly GetDateOnly(this DateTime dt)
        {
            return new DateOnly
            {
                Day = dt.Day,
                Month = dt.Month,
                Year = dt.Year
            };
        }
    }
    

    Usage

    DateTime dt = DateTime.Now;
    DateOnly result = dt.GetDateOnly();
    

提交回复
热议问题