Resolved [2005] Just can't get a string to format
I have a 'date' string value of "19561206" which is 12/06/1956 but for the life of me I can't get a format/converter that will convert this to a ShortDateString. I would also gladly settle to just format the string as it is to "12/06/1956" ( I can do that very manually but looking for a better way).
Does anyone have a slick way to do this?
Edit:
Thanks for the input... we landed up simply formatting the string to "1956-12-06" then crunching it through DateTime.TryParse().ToShortDateString() and that worked just fine. Sloppy but meets the needs for now.
Re: [2005] Just can't get a string to format
If the "date" is only in a string object, then there is really no slick way of doing it... Unless you can read it into a new Date... But I'm sure that isn't working for you.
Re: [2005] Just can't get a string to format
Named groups in regular expressions would solve this problem. Assuming the input is yyyyMMdd, and output is MM/dd/yyyy:
Code:
string input = "19561206";
string output = Regex.Replace(input,
@"(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})",
"${month}/${day}/${year}");
Re: Resolved [2005] Just can't get a string to format
You can also use String.Substring to parse out different parts of the date and the reconstruct it to a dateTime object. Since you know the format of the date string, it wouldn't be too hard.
Re: Resolved [2005] Just can't get a string to format
Quote:
Originally Posted by stanav
You can also use String.Substring to parse out different parts of the date and the reconstruct it to a dateTime object. Since you know the format of the date string, it wouldn't be too hard.
Or, we could use framework provided DateTime.ParseExact method ;)
Code:
string input = "19561221";
DateTime stringParsed = new DateTime(int.Parse(input.Substring(0, 4)),
int.Parse(input.Substring(4, 2)),
int.Parse(input.Substring(6, 2)));
Console.WriteLine(stringParsed.ToLongDateString());
DateTime exactParse = DateTime.ParseExact(input,
"yyyyMMdd",
Thread.CurrentThread.CurrentCulture.DateTimeFormat,
DateTimeStyles.AssumeLocal);
Console.WriteLine(exactParse.ToLongDateString());
string directToFormat = Regex.Replace(input,
@"(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})",
"${month}/${day}/${year}");
Console.WriteLine(directToFormat);