Thursday, March 3, 2011

Parsing a Date Range in C# - ASP.NET

Given say 11/13/2008 - 12/11/2008 as the value posted back in TextBox, what would be the best way to parse out the start and end date using C#?

I know I could use:

DateTime startDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(0, 10));
DateTime endDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(13, 10));

Is there a better way?

From stackoverflow
  • var dates = TextBoxDateRange.Text.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
    
    var startDate = DateTime.Parse(dates[0], CultureInfo.CurrentCulture);
    var endDate = DateTime.Parse(dates[1], CultureInfo.CurrentCulture);
    
  • Instead of Convert.ToDateTime, it could be worth to use DateTime.Parse and explicitely put in the Culture you desire. If I try that example with any European Culture, i get an Error because 11/13/2008 points to the 11th Day in the 13th Month of 2008...

            CultureInfo ci = new CultureInfo("en-us");
            var startDate = DateTime.Parse(components[0], ci);
    

0 comments:

Post a Comment