-1

I need to get only the date not the hour from this:

DateTime.Parse(tr.SelectSingleNode(".//td[@class='full-date']").InnerText.Trim()).Date;

but I get this result:

3/24/2018 12:00:00 AM

How can I get only:

3/24/2018

Note that I save the result in the following format:

public DateTime Date { get; set; }
Mong Zhu
  • 20,890
  • 7
  • 33
  • 66
  • 3
    Your datetime object is what it says it is `Date` + `Time`... you can't make a datetime object with only a date, it will have time 00:00 (24hrs notation) by default – EpicKip Sep 14 '17 at 11:35
  • I can't set only "Date" object in the property – Mario Serda Sep 14 '17 at 11:36
  • ugh, just leave it at 00.00 whats the issue? That way you have whole days – EpicKip Sep 14 '17 at 11:37
  • Have you tried formatting it in your desired format ? Like ToString("dd-MM-yyyy") – Saurabh Sep 14 '17 at 11:37
  • Possible duplicate of [How to remove time portion of date in C# in DateTime object only?](https://stackoverflow.com/questions/6121271/how-to-remove-time-portion-of-date-in-c-sharp-in-datetime-object-only) – EpicKip Sep 14 '17 at 11:38
  • and in wpf how can tell to display only date? – Mario Serda Sep 14 '17 at 11:39
  • 1
    @MarioSerda use `{Binding YourDateTimeProperty, StringFormat={}{0:dd/MM/yyyy}"` – SᴇM Sep 14 '17 at 11:40
  • @MarioSerda If its about displaying (which has nothing to do with wpf...) use `dateTimeObject.ToString("Mdyyyy");` – EpicKip Sep 14 '17 at 11:46

4 Answers4

6

Note that I save the result in the following format:

you save the result in a variable of type DateTime you don't save in in a certain format. Only the string representation of DateTime has a format. DateTime has always both, date and time ( I guess hence the name ;))

How can I get only: 3/24/2018 ?

this point becomes important when you try to get the string representation of the DateTime using this overload of the ToString method:

string string_representation = Date.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
Mong Zhu
  • 20,890
  • 7
  • 33
  • 66
2

You can't remove the time component from System.DateTime. You could create your own Date representation if you wish. Or, you could get the date string using,

Date.ToString("MM/dd/yyyy")
Nisarg
  • 13,121
  • 5
  • 31
  • 48
1

How about this?

        DateTime time = DateTime.Now;
        Console.WriteLine(time.ToString("MM/dd/yy"));
1

Consider using NodaTime, which has the concept of a date without time (and vice versa).

To convert from DateTime to LocalDate:

using System;
using NodaTime;

namespace YourApp.Extensions
{
    public static class NodaTimeExtensions
    {
        public static LocalDate ToNodaLocalDate(this DateTime dateTime)
        {
            return new LocalDate(dateTime.Year, dateTime.Month, dateTime.Day);
        }
    }
}
mjwills
  • 21,750
  • 6
  • 36
  • 59