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

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

    This way of get only date without time

    DateTime date = DateTime.Now;
    string Strdateonly = date.ToString("d");
    

    Output = 5/16/2015

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

    Use date.ToShortDateString() to get the date without the time component

    var date = DateTime.Now
    var shortDate = date.ToShortDateString() //will give you 16/01/2019
    

    use date.ToString() to customize the format of the date

    var date = DateTime.Now
    var shortDate = date.ToString('dd-MMM-yyyy') //will give you 16-Jan-2019
    
    0 讨论(0)
  • 2020-11-22 09:55

    Try to make your own Structure for that. DateTime object will have date and time both

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

    Came across this post when trying to solve the original Q.

    I am using Asp.Net and after some research I have found when you are binding to the value of the date in code behind, you can drop the time so it will not display on screen.

    C#:

    DateTime Today = DateTime.Now;
    

    aspx:

    <%: this.Today.ToShortDateString() %>
    
    0 讨论(0)
  • 2020-11-22 09:57

    You Can Try This for the Only Date From the Datetime

    String.Format("{0:d/M/YYYY}",dt);
    

    Where dt is the DateTime

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

    I know this is an old post with many answers, but I haven't seen this way of removing the time portion. Suppose you have a DateTime variable called myDate, with the date with time part. You can create a new DateTime object from it, without the time part, using this constructor:

    public DateTime(int year, int month, int day);
    

    Like this:

    myDate = new DateTime(myDate.Year, myDate.Month, myDate.Day);
    

    This way you create a new DateTime object based on the old one, with 00:00:00 as time part.

    0 讨论(0)
提交回复
热议问题