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

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

    The Date property will return the date at midnight.

    One option could be to get the individual values (day/month/year) separately and store it in the type you want.

    var dateAndTime = DateTime.Now; 
    int year = dateAndTime.Year;
    int month = dateAndTime.Month;
    int day = dateAndTime.Day;
    
    string.Format("{0}/{1}/{2}", month, day, year);
    
    0 讨论(0)
  • You can't. A DateTime in .NET always have a time, defaulting to 00:00:00:000. The Date property of a DateTime is also a DateTime (!), thus having a time defaulting to 00:00:00:000 as well.

    This is a shortage in the .NET Framework, and it could be argued that DateTime in .NET violates the Single Responsibility Principle.

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

    This could be simply done this way:

    var dateOnly = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day)
    
    0 讨论(0)
  • 2020-11-22 09:47

    To get only the date portion use the ToString() method,

    example: DateTime.Now.Date.ToString("dd/MM/yyyy")

    Note: The mm in the dd/MM/yyyy format must be capitalized

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

    Use a bit of RegEx:

    Regex.Match(Date.Now.ToString(), @"^.*?(?= )");
    

    Produces a date in the format: dd/mm/yyyy

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

    Use the method ToShortDateString. See the documentation http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx

    var dateTimeNow = DateTime.Now; // Return 00/00/0000 00:00:00
    var dateOnlyString = dateTimeNow.ToShortDateString(); //Return 00/00/0000
    
    0 讨论(0)
提交回复
热议问题