0

My sample code for solving this problem:

    public class Person
    {
        private DateTime _date;
        public string Name { get; set; }
        public DateTime DateOfBirth { get { return _date.Date; } set { _date = value; } }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.Name = "AAA";
            p.DateOfBirth = new DateTime(2005,3,2,5,5,5);

            Console.WriteLine(p.DateOfBirth);
            Console.ReadKey();
        }
    }

In this case output is:

02.03.2005 00:00:00

Technically it removed the time, but still returns 00:00:00 as an hour. How can i actually get rid of time? A lot of people post this as solution, but it doesn't really solve the problem.

My expected output is:

02.03.2005
  • Do you want a string representation with out the time or an `DateTime` instance without time? – Ackdari May 12 '20 at 10:36
  • [DateTime.Date Property](https://docs.microsoft.com/en-us/dotnet/api/system.datetime.date?view=netcore-3.1) and use corresponding [format](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings) to convert to needed string representation. – Guru Stron May 12 '20 at 10:36
  • you can use ``p.DateOfBirth.ToShortDateString()`` – Mohammed Sajid May 12 '20 at 10:37
  • https://stackoverflow.com/questions/6121271/how-to-remove-time-portion-of-date-in-c-sharp-in-datetime-object-only – Noorul May 12 '20 at 10:58
  • Does this answer your question? [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) – user4157124 May 12 '20 at 22:22

3 Answers3

0

You'll need to tell it a format specifier;

Console.WriteLine(p.DateOfBirth.ToString("..."));

where "..." is your choice; "d" maybe (short date). See standard and custom formats.

Marc Gravell
  • 927,783
  • 236
  • 2,422
  • 2,784
0

you need to format the date refer https://www.csharp-examples.net/string-format-datetime/

alternatively you can use .ToString() with specified format,

0

you can use below code

Console.WriteLine(p.DateOfBirth.ToString("MM.dd.yyyy"));

place MM for month dd for day of month as per your convenience

Prakash
  • 418
  • 1
  • 4
  • 14