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

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 2
    strings are immutable. `.Insert` returns a new string. – ProgrammingLlama Jan 31 '19 at 00:36
  • You should take a look at [this](https://stackoverflow.com/q/2560540/416574) 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. – pstrjds Jan 31 '19 at 00:40

1 Answers1

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.

David
  • 208,112
  • 36
  • 198
  • 279