I am currently working on a project and having a little problem. The project is in .NET core and has to do with a DateTime validation. Let's start of by saying that I am quite new to C# and .NET.
I have a dropdown with a few weeks in it (begin and end of the week). From this I extract the beginning of the week like: 14-12-2020 - 19-12-2020 => 14-12-2020. The code below is to make sure that you can only choose a week that is in the future. There should never be a normal instance that this happens but with inspect elements this can happen.
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
DateTime todayWeek = DateTime.Today;
DateTime startOfWeek = todayWeek.AddDays(-1 * (int)todayWeek.DayOfWeek + 1);
if (FutureWeek != null)
{
string dateString = FutureWeek.Split(' ').First(); // Cut off everything at first whitespace
DateTime futureWeekDate = DateTime.Parse(dateString);
if (futureWeekDate < startOfWeek)
{
yield return new ValidationResult($"The chosen week can't be in the past");
}
}
}
This code works fine if I use the Dutch / EU date format (dd/mm/yyyy) on my local pc. But as soon as I change the date format to US (mm/dd/yyyy) on my local pc I run into problems where the string (14/12/2020) is not a valid datetime because it expects the American format and there is no 14th month.
Is there a solution in which I can specify a global time format to be used across the whole project, to make sure that the local time format is not influencing my program?