Search code examples
c#.net-3.5

Changing position of words in a string


I have a string let say,

string temp1 = "25 10 2012"

but I want this,

"2012 10 25"

what would be the best way of doing it. format will always be like this.


Solution

  • Looks like its a date. You can parse the string to DateTime, using DateTime.ParseExact and then use .ToString to return formatted result.

    DateTime dt = DateTime.ParseExact(temp1, "dd MM yyyy", CultureInfo.InvariantCulture);
    Console.Write(dt.ToString("yyyy MM dd"));
    

    You may use that DateTime object later in your code, and also apply different formatting (if you need)