-1

I'm getting from API DateTime.Date, that means Date without time, and sometimes I'm getting DateTime with full valid date, but in case when I'm getting value without Time and since property is type of DateTime it will include also time but with value of zeros.

So my string looks like this:

29/08/2019 00:00:00

How could I recognize when it's without valid Time and remove this 00:00:00 from my string?

Thanks guys

Cheers

Roxy'Pro
  • 3,192
  • 4
  • 23
  • 59
  • 3
    Take a look at [format strings](https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings). – Llama Aug 29 '19 at 09:09
  • @John Sometimes I'm getting full DateTime value, I need to recognize when it's with zeros and format it.. – Roxy'Pro Aug 29 '19 at 09:11
  • That's not what you asked in your question, although you could check `if (dt.Date == dt)` if you first parse it to a `DateTime` object (`dt`). – Llama Aug 29 '19 at 09:12
  • 1
    @Roxy'Pro You can use `if (dt.TimeOfDay.Ticks == 0) ...` to check whether dt represents midnight. – Thorsten Dittmar Aug 29 '19 at 09:14

1 Answers1

1

Parse it an then use ToShortDateString or ToString("d"):

string result = DateTime.Parse("29/08/2019 00:00:00").ToShortDateString();

Sometimes I'm getting full DateTime value (with valid Time part), so I need to recognize when it's with zeros and format it.. to short date string, I can not use it in every case

Well, then compare the DateTime with it's own Date property:

string dateString = "29/08/2019 01:00:00"; // with this sample the 'if' will not be entered because there is a time portion
DateTime dt = DateTime.Parse(dateString);
if(dt.Date == dt)
{
    // there is no time portion in this DateTime
    dateString = dt.ToShortDateString();
}
Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
  • Sometimes I'm getting full DateTime value (with valid Time part), so I need to recognize when it's with zeros and format it.. to short date string, I can not use it in every case – Roxy'Pro Aug 29 '19 at 09:12
  • You can use `if (dt.TimeOfDay.Ticks == 0) ...` to check whether `dt` represents midnight. – Thorsten Dittmar Aug 29 '19 at 09:14
  • @TimSchmelter You are the man! Thx! Any recommended resources on c# learning? – Roxy'Pro Aug 29 '19 at 12:36