fishmong3r
fishmong3r

Reputation: 1434

string.substring fails on my strings

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?

Upvotes: 0

Views: 112

Answers (2)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

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.

Upvotes: 4

Soner Gönül
Soner Gönül

Reputation: 98750

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
}

Upvotes: 7

Related Questions