-1

My input strings are of the format:

string a = "201101..";
string b = "199008..";
string c = "20110202";

How do I convert them to a date format of yyyymmdd?

I know I can use DateTime.TryParse() on the 3rd type.

Here's what I have:

string tempdate = a;
DateTime actualdate;
char[] charsToTrim = { '.' };
tempdate = tempdate.TrimEnd(charsToTrim);
if (DateTime.TryParse(tempdate, out actualdate))
{
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
sam
  • 320
  • 3
  • 14
  • 2
    201101 doesn't match yyyymmdd, it has no days – Kevin DiTraglia Oct 08 '13 at 18:21
  • 2
    What are the expected results for the 1st and 2nd input? – dtb Oct 08 '13 at 18:23
  • 3
    One solution may be to parse out what you know you have. So if you know you have six characters and are expecting 8 in yyyyMMdd, you can say that the first six are yyyyMM. Then your year string is p.SubString(0, 4) and your Month string is p.SubString(3, 2) I think. This is an off the cuff comment answer just to get you thinking and may not be accurate. – Todd Richardson Oct 08 '13 at 18:24
  • You'll probably end up having to implement your own parser. – Geeky Guy Oct 08 '13 at 18:29
  • [Garbage in, garbage out](http://en.wikipedia.org/wiki/Garbage_in,_garbage_out) - if strings are invalid than you can simply use fixed invalid date as result. Also your sample seem to be values with fixed field size which should be handled with `Substring` and `int.Parse` as @ToddRichardson suggested. – Alexei Levenkov Oct 08 '13 at 18:29
  • Thats how the value is stored in the database.. the date is unknown. I decided to add the dates as 01. string p ="201101.."; string tempdate; string format = "yyyymmdd"; char[] charsToTrim = { '.' }; tempdate = p.TrimEnd(charsToTrim); DateTime actualdate; tempdate +="01"; actualdate=DateTime.ParseExact(tempdate,format,CultureInfo.InvariantCulture); – sam Oct 08 '13 at 18:38

5 Answers5

8

You can pass multiple formats with DateTime.TryParseExact

List<string> strDates = new List<string>
{
    "201101..",
    "199008..",
    "20110202",
};
string[] possibleFormats = new[] { "yyyyMM", "yyyydd", "yyyyMd" }; 
                                                     //single M and d to parse
                                                    //both single and double digit
                                                    //Month or Day



DateTime dt; 

foreach(string str in strDates)
{
    if (DateTime.TryParseExact(str.Trim('.'), 
                            possibleFormats, 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None, 
                            out dt))
    {
        Console.WriteLine(dt);
    }
    else
    {
        Console.WriteLine("Invalid date");
    }
}

The above would give you the output:

01/01/2011 12:00:00 AM
01/08/1990 12:00:00 AM
02/02/2011 12:00:00 AM
Habib
  • 219,104
  • 29
  • 407
  • 436
  • I think i have it: string p ="201101.."; string tempdate; string format = "yyyymmdd"; char[] charsToTrim = { '.' }; tempdate = p.TrimEnd(charsToTrim); DateTime actualdate; tempdate +="01"; actualdate=DateTime.ParseExact(tempdate,format,CultureInfo.InvariantCulture); – sam Oct 08 '13 at 18:39
  • @sam, you don't need string concatenation, also use `MM` for month, lower case `mm` is for minutes. – Habib Oct 08 '13 at 18:41
  • Got it. But what if i need to display the date as yyyyMMdd? – sam Oct 08 '13 at 18:47
  • @sam, just do `Console.WriteLine(dt.ToString("yyyyMMdd"));` – Habib Oct 08 '13 at 18:51
  • private string FormattedDate(string p) { string[] possibleFormats = new[] { "yyyyMM", "yyyyMMdd", "yyyyMM'..'" }; DateTime dt; char[] charsToTrim = {'.'}; if (p != null) { DateTime.TryParseExact(p.Trim(charsToTrim), possibleFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt); p = dt.ToString("yyyyMMdd"); } return p ; } – sam Oct 08 '13 at 19:09
  • @sam, it looks fine, You can change `p.Trim(charsToTrim)` to `p.Trim('.')` if you have just one character to trim. – Habib Oct 08 '13 at 20:41
2

You could use DateTime.TryParseExtract method to specify the format of your dateTime object and it will try to convert for you, for sample:

if (DateTime.TryParseExact(tempdate, "yyyyMMdd", null, DateTimeStyles.None, out actualdate))
{
  // conversion ok
  // use the actualdate object
}
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
  • 3
    It should probably be "yyyyMMdd" as the second parameter to match the question. –  Oct 08 '13 at 18:21
2

Small addendum to Habib's answer:

string[] possibleFormats = new[] { "yyyyMMdd", "yyyyMM'..'" };
                                                      ↑↑↑↑
DateTime result;
if (DateTime.TryParseExact("201310..", possibleFormats, null, 0, out result))
{
    // result == {01/10/2013 00:00:00}
}

That is, you can have the two dots in the expected format string and don't need to strip them off first.

Community
  • 1
  • 1
dtb
  • 213,145
  • 36
  • 401
  • 431
1

Take a look at DateTime.ParseExact. I think it could be usefull. And take a look at this article

Community
  • 1
  • 1
1

Maybe something alone these lines will help:

private DateTime GetDateTime(string tempDate)
{
    DateTime actualdate;
    if (tempDate.Contains('.'))
    {
       DateTime.TryParseExact(tempdate.SubString(0,6), "yyyymm", out actualdate)
    }
    else 
    {
        DateTime.TryParseExact(tempdate, "yyyymmdd", out actualdate)
    }

    return actualdate;
}
Bit
  • 1,068
  • 1
  • 11
  • 20