1

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?

  • Welcome to the site. You should add the language tag (and possibly additional relevant tags). We have too many question, so we usually filter questions by tag. In case of this question, you may have much less relevant reader. – Giacomo Catenazzi Dec 09 '20 at 14:57

1 Answers1

0

If I understand correctly, you may want to set the way your date is formatted. That way it is always the same.

DateTime.Now.ToString("MM/dd/yyyy")

See this c sharp corner for more detailed information and for source code on the answer:

Date formatting

Edit: you can use different forms. So you can also start with the years, days, add more options. Feel free to ask for more information or if you keep on hitting the roadblock.

Mitchell
  • 55
  • 7