Lawraoke
Lawraoke

Reputation: 556

C# .Date syntax

I am trying to working on Date instead of DateTime in C#, which it will only return me Date: 01/01/2001 instead of DateTime: 01/01/2001 12:00:00 AM. I had browse through stackoverflow and I hit this .Date example

so here I try:

while (obj.Read())
   {
      var pdate = Convert.ToDateTime(obj["PurchaseDate"]);
      var edate = Convert.ToDateTime(obj["ExpiredDate"]);
      class.Add(new myClass()
           {
               PurchaseDate = pdate.Date.ToString(),
               ExpiredDate = edate.Date.ToString(),
           }
   );
}

I am trying to get data using query, and here I return a <List> and I tried to use .Date, However, I still get the format of DateTime: 01/01/2001 12:00:00 AM

May I know that is it my syntax error or is there had a better way to perform such action?

**My PurchaseDate and ExpiredDate is a string


Update

Thanks for answers from Kirin and Kevin

My code worked and change to follows:

var pdate = Convert.ToDateTime(obj["PurchaseDate"]);
var edate = Convert.ToDateTime(obj["ExpiredDate"]);
class.Add(new myClass()
{
   PurchaseDate = pdate.ToString("dd/MM/yyyy"),
   ExpiredDate = edate.ToString("dd/MM/yyyy"),
}

Upvotes: 0

Views: 112

Answers (2)

Kevin Brydon
Kevin Brydon

Reputation: 13102

That's just how DateTime.Date works according to the documentation. DateTime.Date returns:

A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00).

If you want just the day month and year you need to format it

var pdate = Convert.ToDateTime(obj["PurchaseDate"]).ToString("dd/MM/yyyy");

See: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.date?view=netcore-3.1

Upvotes: 2

Kirin Yao
Kirin Yao

Reputation: 1636

The .Date still return an object of DateTime type which includes the time part. Try ToString("MM/dd/yyyy").

Upvotes: 2

Related Questions