Parsing date range in C # - ASP.NET

Said 11/13/2008 - 12/11/2008 as the value posted back to the TextBox would be the best way to parse the start and end date using C #?

I know I can use:

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

      

Is there a better way?

+1


source to share


2 answers


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);

      



+8


source


Instead of Convert.ToDateTime it might be worth using DateTime.Parse and explicitly putting in the desired Culture. If I try this 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);

      

+2


source







All Articles