C# Formatting DateTime String Value

nightshadz
nightshadz used Ask the Experts™
on
I am formatting a date & time string value that is retrieved from an XML file and needs to be in this format: "yyyy-MM-dd HH:mm:ss:ff"

The string value I am working with is: "2011122818083869"

I have this working by creating 3 integer arrays with the positions for where I need to insert the dashes, spaces, and colons, but I'm curious if there is a more elegant way to code this in C#?

int[] dash = { 4, 7 };
int[] space = { 10 };
int[] colon = { 13, 16, 19 };
string s = attr.Value.Insert(dash[0], "-").Insert(dash[1], "-").Insert(space[0], " ").Insert(colon[0], ":").Insert(colon[1], ":").Insert(colon[2], ":");

Open in new window


The output returns "2011-12-28 18:08:38:69".

Thanks in advance!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016
Commented:
Hi,

You could use regex
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern =  @"(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})";
      string input = "2011122818083869";
      string replacement = "$1-$2-$3 $4:$5:$6:$7";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);

      Console.WriteLine("Original String:    '{0}'", input);
      Console.WriteLine("Replacement String: '{0}'", result);                             
   }
}

Open in new window

Regards
Most Valuable Expert 2015
Distinguished Expert 2018
Commented:
You can just parse to true datetime, then format this using standard methods:

string input = "2011122818083869";

System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
DateTime date = DateTime.ParseExact(input, "yyyyMMddHHmmssff", provider);

string formattedDate = date.ToString("yyyy'-'MM'-'dd HH':'mm':'ss':'ff");

Console.WriteLine (formattedDate);

Open in new window

/gustav
Retired
Distinguished Expert 2017
Commented:
This should do what you need.
string dtStr = "2011122818083869";
var dtFormat = DateTime.ParseExact(dtStr, "yyyyMMddHHmmssFFFFFFF", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd HH:mm:ss:ff");

Open in new window

Author

Commented:
Thanks everyone!
Most Valuable Expert 2015
Distinguished Expert 2018
Commented:
You are welcome!

Please note that the format string for ParseExact must be, well, exact. See my code.

/gustav

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial