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

后端 未结 30 3378
醉话见心
醉话见心 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

    DateTime.Date

    var newDate = DateTime.Now; //newDate.Date property is date portion of DateTime
    
    0 讨论(0)
  • 2020-11-22 09:32

    I wrote a DateOnly structure. This uses a DateTime under the skin but no time parts are exposed publically:

    using System;
    
    public struct DateOnly : IComparable, IFormattable, IComparable<DateOnly>, IEquatable<DateOnly>
    {
    
        private DateTime _dateValue;
    
        public int CompareTo(object obj)
        {
            if (obj == null)
            {
                return 1;
            }
    
            DateOnly otherDateOnly = (DateOnly)obj;
            if (otherDateOnly != null)
            {
                return ToDateTime().CompareTo(otherDateOnly.ToDateTime());
            }
            else
            {
                throw new ArgumentException("Object is not a DateOnly");
            }
        }
    
        int IComparable<DateOnly>.CompareTo(DateOnly other)
        {
            return this.CompareToOfT(other);
        }
        public int CompareToOfT(DateOnly other)
        {
            // If other is not a valid object reference, this instance is greater.
            if (other == new DateOnly())
            {
                return 1;
            }
            return this.ToDateTime().CompareTo(other.ToDateTime());
        }
    
        bool IEquatable<DateOnly>.Equals(DateOnly other)
        {
            return this.EqualsOfT(other);
        }
        public bool EqualsOfT(DateOnly other)
        {
            if (other == new DateOnly())
            {
                return false;
            }
    
            if (this.Year == other.Year && this.Month == other.Month && this.Day == other.Day)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    
        public static DateOnly Now()
        {
            return new DateOnly(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
        }
    
        public static bool TryParse(string s, ref DateOnly result)
        {
            DateTime dateValue = default(DateTime);
            if (DateTime.TryParse(s, out dateValue))
            {
                result = new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
                return true;
            }
            else
            {
                return false;
            }
        }
    
        public static DateOnly Parse(string s)
        {
            DateTime dateValue = default(DateTime);
            dateValue = DateTime.Parse(s);
            return new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
        }
    
        public static DateOnly ParseExact(string s, string format)
        {
            CultureInfo provider = CultureInfo.InvariantCulture;
            DateTime dateValue = default(DateTime);
            dateValue = DateTime.ParseExact(s, format, provider);
            return new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
        }
    
        public DateOnly(int yearValue, int monthValue, int dayValue) : this()
        {
            Year = yearValue;
            Month = monthValue;
            Day = dayValue;
        }
    
        public DateOnly AddDays(double value)
        {
            DateTime d = new DateTime(this.Year, this.Month, this.Day);
            d = d.AddDays(value);
            return new DateOnly(d.Year, d.Month, d.Day);
        }
    
        public DateOnly AddMonths(int months)
        {
            DateTime d = new DateTime(this.Year, this.Month, this.Day);
            d = d.AddMonths(months);
            return new DateOnly(d.Year, d.Month, d.Day);
        }
    
        public DateOnly AddYears(int years)
        {
            DateTime d = new DateTime(this.Year, this.Month, this.Day);
            d = d.AddYears(years);
            return new DateOnly(d.Year, d.Month, d.Day);
        }
    
        public DayOfWeek DayOfWeek
        {
            get
            {
                return _dateValue.DayOfWeek;
            }
        }
    
        public DateTime ToDateTime()
        {
            return _dateValue;
        }
    
        public int Year
        {
            get
            {
                return _dateValue.Year;
            }
            set
            {
                _dateValue = new DateTime(value, Month, Day);
            }
        }
    
        public int Month
        {
            get
            {
                return _dateValue.Month;
            }
            set
            {
                _dateValue = new DateTime(Year, value, Day);
            }
        }
    
        public int Day
        {
            get
            {
                return _dateValue.Day;
            }
            set
            {
                _dateValue = new DateTime(Year, Month, value);
            }
        }
    
        public static bool operator == (DateOnly aDateOnly1, DateOnly aDateOnly2)
        {
            return (aDateOnly1.ToDateTime() == aDateOnly2.ToDateTime());
        }
    
        public static bool operator != (DateOnly aDateOnly1, DateOnly aDateOnly2)
        {
            return (aDateOnly1.ToDateTime() != aDateOnly2.ToDateTime());
        }
    
        public static bool operator > (DateOnly aDateOnly1, DateOnly aDateOnly2)
        {
            return (aDateOnly1.ToDateTime() > aDateOnly2.ToDateTime());
        }
    
        public static bool operator < (DateOnly aDateOnly1, DateOnly aDateOnly2)
        {
            return (aDateOnly1.ToDateTime() < aDateOnly2.ToDateTime());
        }
    
        public static bool operator >= (DateOnly aDateOnly1, DateOnly aDateOnly2)
        {
            return (aDateOnly1.ToDateTime() >= aDateOnly2.ToDateTime());
        }
    
        public static bool operator <= (DateOnly aDateOnly1, DateOnly aDateOnly2)
        {
            return (aDateOnly1.ToDateTime() <= aDateOnly2.ToDateTime());
        }
    
        public static TimeSpan operator - (DateOnly aDateOnly1, DateOnly aDateOnly2)
        {
            return (aDateOnly1.ToDateTime() - aDateOnly2.ToDateTime());
        }
    
    
        public override string ToString()
        {
            return _dateValue.ToShortDateString();
        }
    
        public string ToString(string format)
        {
            return _dateValue.ToString(format);
        }
    
        public string ToString(string fmt, IFormatProvider provider)
        {
            return string.Format("{0:" + fmt + "}", _dateValue);
        }
    
        public string ToShortDateString()
        {
            return _dateValue.ToShortDateString();
        }
    
        public string ToDbFormat()
        {
            return string.Format("{0:yyyy-MM-dd}", _dateValue);
        }
    }
    

    This is converted from VB.NET, so apologies if some conversions are not 100%

    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-11-22 09:33

    Here is another method using String.Format

        DateTime todaysDate = DateTime.UtcNow;
    
        string dateString = String.Format("{0:dd/MM/yyyy}", todaysDate);
    
        Console.WriteLine("Date with Time: "+ todaysDate.ToString());
    
        Console.WriteLine("Date Only : " + dateString);
    

    Output:

    Date with Time: 9/4/2016 11:42:16 AM
    
    Date Only : 04/09/2016
    

    This also works if the Date Time is stored in database.

    For More Date and Time formatting check these links:

    Reference 1

    Reference 2

    Hope helps.

    0 讨论(0)
  • 2020-11-22 09:35

    Use .Date of a DateTime object will ignore the time portion.

    Here is code:

    DateTime dateA = DateTime.Now;
    DateTime dateB = DateTime.Now.AddHours(1).AddMinutes(10).AddSeconds(14);
    Console.WriteLine("Date A: {0}",dateA.ToString("o"));
    Console.WriteLine("Date B: {0}", dateB.ToString("o"));
    Console.WriteLine(String.Format("Comparing objects A==B? {0}", dateA.Equals(dateB)));
    Console.WriteLine(String.Format("Comparing ONLY Date property A==B? {0}", dateA.Date.Equals(dateB.Date)));
    Console.ReadLine();
    

    Output:

    >Date A: 2014-09-04T07:53:14.6404013+02:00
    >Date B: 2014-09-04T09:03:28.6414014+02:00
    >Comparing objects A==B? False
    >Comparing ONLY Date property A==B? True
    
    0 讨论(0)
  • 2020-11-22 09:36

    use

    DateTime.Now.ToString("dd-MM-yyyy");
    
    0 讨论(0)
提交回复
热议问题