-7

I have two dates.

ReleaseDates = "11/2/2016";
LiveDate =  "11/02/2016";

In the above two dates are same. But in my below coding it returns FALSE.

if (ReleaseDates.Contains(LiveDate.TrimStart(new Char[] { '0' })))
 {

 }
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
TechGuy
  • 4,298
  • 15
  • 56
  • 87
  • can you use `DateTime` instead of strings?.. If you parse to `DateTime` then it is trivial – Gilad Green Nov 02 '16 at 10:46
  • Perhaps you want to parse them as dates and compare that? – Andrei Nov 02 '16 at 10:46
  • 2
    Well one of the values is `11/2/2016` and another is `11/02/2016` so of course they're not the same - `LiveDate.TrimStart(new Char[] { '0' })` might not work how you think, it'll remove a `0` from the beginning of the string for example if it was instead `011/2/2016` it would become `11/2/2016` – Alfie Goodacre Nov 02 '16 at 10:46
  • 6
    I would never understand why using strings for dates. Never. – Pikoh Nov 02 '16 at 10:47
  • 1
    `TrimStart` removes only **leading** occurrences of a set of characters –  Nov 02 '16 at 10:47
  • 1
    _I have two dates_ - No you don't, you have two _strings_. You would be better off using `DateTime.TryParseExact` to convert them both to dates and then compare them. – Chris Dunaway Nov 02 '16 at 15:16

2 Answers2

2

Your code does not work because TrimStart removes characters at the start of the string. It looks like LiveDate has no zeros at the beginning; the character '0' that you want to trim is at index 3, preceded by other characters. That is why it is not getting trimmed.

Comparing strings representing dates is an error-prone strategy. You would be better off parsing both strings, and comparing the results as DateTime objects.

In general, you should keep dates as objects designed for date representation - for example, DateTime or DateTimeOffset. This would let you customize date representation for display purposes, and avoid errors when date format changes from mm/dd to dd/mm.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

This is because you are not comparing dates, you are comparing two strings that are not the same. Your best shot here is parsing first and then comparing.

DateTime releaseDate = DateTime.Parse(ReleaseDates);
DateTime liveDate = DateTime.Parse(LiveDate);
if (releaseDate == liveDate) // This should be true.
{
    // Do stuff.
}
Yeray Cabello
  • 411
  • 3
  • 12