VBForums >
.NET >
C# > Resolved [2005] Just can't get a string to format
Click to See Complete Forum and Search --> : Resolved [2005] Just can't get a string to format
VBGuy
Nov 2nd, 2007, 10:12 AM
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.
MetalKid
Nov 2nd, 2007, 11:25 AM
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.
axion_sa
Nov 2nd, 2007, 12:17 PM
Named groups in regular expressions would solve this problem. Assuming the input is yyyyMMdd, and output is MM/dd/yyyy:
string input = "19561206";
string output = Regex.Replace(input,
@"(?<year>\d{4})(?<month>\d{2})(?<day>\d{2})",
"${month}/${day}/${year}");
stanav
Nov 6th, 2007, 10:19 AM
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.
axion_sa
Nov 6th, 2007, 04:32 PM
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 ;)
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);
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.