0

I have the below piece of code:

string date = dtxt.Substring(5, 2) + @"/" + dtxt.Substring(7, 2) + @"/" + dtxt.Substring(0, 4);

The text I'm trying to parse with it is yyyyMMdd. So from 20150309 I need 03/09/2015. I don't use dateTime format as both the input and output are strings.

The issue is I get ArgumentOutOfRangeException. string.Substring(X, Y) should get the substring from the X index for Y length, shouldn't it?

2
  • 2
    Hint: indexes are 0-based. So a substring of "20150309" starting at index 7 will start with 9, and can only have a length of 1... Commented Mar 9, 2015 at 11:13
  • 2
    You are getting the error because the parameters should be (4,2), (6, 2) and (0, 4). However, you should use the date functions as others have suggested. Commented Mar 9, 2015 at 11:14

2 Answers 2

7

Don't use string operations in such a case.

Parse it to DateTime and format it with .ToString() method like;

string s = "20150309";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture).Dump(); //03/09/2015
}
Sign up to request clarification or add additional context in comments.

Comments

4

You can convert this to DateTime and then back to any string represantaion with the help of ToString(string format, IFormatProvider provider) overload:

 var result = DateTime.ParseExact(dtxt, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None)
                      .ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

And don't forget to pass CultureInfo.InvariantCulture as input while parsing. Not all cultures use the same format for dates and decimal currency values. Invariant culture is a special culture that you can always use in any .NET application.


By the way, the reason of exception in your code is you have not found the starting indices of month and day properly. You can change your code as:

string date = dtxt.Substring(4, 2) + @"/" + dtxt.Substring(6, 2) + @"/" + dtxt.Substring(0, 4);

But, of course it is not recommended to use operations on strings like this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.