0

I am working on changing these strings into this format yyyy-mm-ddhh:mm:ss

I put the strings into an array, fed it into a four each loop where I am using the Insert() function to add the "-" and ":" in the appropriate positions but it is still printing out the original strings.

    static void Main(string[] args)
    {
        string[] dates =  { "20190127144251", "20190127123315", "20190127035942" };

        foreach (string i in dates)
        {
            string str = i;
            str.Insert(3, "-");
            str.Insert(5, "-");
            str.Insert(7, "-");
            str.Insert(9, ":");
            str.Insert(11, ":");


            Console.WriteLine(i);

        }


    }
}

Printing out the original string, not formatted

2
  • 2
    strings are immutable. .Insert returns a new string. Commented Jan 31, 2019 at 0:36
  • You should take a look at this question as it shows you how to use DateTime.TryParseExact. I would recommend parsing into a DateTime object and then use the ToString method with your format string. Commented Jan 31, 2019 at 0:40

1 Answer 1

4

First, you're not storing the result of your .Insert() calls. Strings are immutable and modifications to them aren't in place but rather return the new modified string. Put the result in the variable:

str = str.Insert(3, "-");
// etc.

Second, you're outputting i intead of str. Output the one you're modifying:

Console.WriteLine(str);

Third, you can skip all of this by parsing the string into an actual DateTime and formatting its output:

foreach (string i in dates)
{
    var dt = DateTime.ParseExact(i, "yyyyMMddhhmmss");
    Console.WriteLine(dt.ToString("yyyy-MM-dd-hh:mm:ss"));
}

Which gives you much cleaner code with more clear intent, rather than counting string indexes and inserting individual characters.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.