'Convert DateTime 1/20/2022 8:48:30 PM to 20/01/2022 8:48:30 PM C#
I basically have two DateTime variables
DateTime dateToday = WorldTimeAPI.Instance.GetCurrentDateTime();
DateTime dateFinish;
dateToday gets current date from the web, with this format 1/20/2022 8:48:30 PM.
dateFinish has this other format 20/01/2022 8:48:30 PM, the day first, and then the month, everything else is the same.
I want to be able to parse one of them to match the other one in terms of format so that I can compare them both to know if todays date is greater than date finish by doing this:
if(dateToday.CompareTo(dateToEndMission) > 0)
{do stuff}
I tried looking at documentation but it has so many different formats that I just couldnt figure out the exact way to do it.
Solution 1:[1]
To compare two dateTime values in an if statement you can do:
if(firstDate.Date > secondDate.Date)
{
//Do something...
}
Solution 2:[2]
Try and keep things as simple as possible.
As stated above you can compare date time with the > operator. But I would go further and ask why you're using that api to get the current date and time when you could just use this
DateTime today = DateTime.Now;
This should fix your problem, because you should be initialising date time in the same way now. If not, then I suggest you take a look at this other questions answers:
Solution 3:[3]
You can try the ParseExact method
DateTime dateToday = DateTime.Now;
DateTime dateFinish = DateTime.ParseExact("20/01/2022 10:56:09", "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
if (dateToday > dateFinish)
{
// do something
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Raoul Montella |
| Solution 2 | Trevor Baker |
| Solution 3 | SaniaGhafur009 |
