Havoux
Havoux

Reputation: 165

C# Converting YYYY-MM-DD to MM/DD/YYYY ("-" TO "/")

Hey I have been having trouble with something.

string record = el.InnerText;
var result1 = parseString(record);
var StartDate = string.Join("", result1.ConvertAll(r => string.Format("{0}", r)).ToArray());
//DateTime strStartDate = DateTime.ParseExact(StartDate, "mm-dd-yyyy", CultureInfo.InvariantCulture);
var EndDate = string.Join("", result1.ConvertAll(r => string.Format("{1}", r)).ToArray());
//DateTime strEndDate = DateTime.ParseExact(EndDate, "mm-dd-yyyy", CultureInfo.InvariantCulture);

This is the parseString function:

private static List<string[]> parseString(string input)
    {
        var pattern = @"Start\s+Date:\s+([0-9-]+)\s+End\s+Date:\s+([0-9-]+)\s+(?:Warranty\s+Type:\s+\w+\s+)?Status:\s+(\w+)\s*";
        return Regex.Matches(input, pattern).Cast<Match>().ToList().ConvertAll(m => new string[] { m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value });
    }

The DateTimes aren't working because I am guessing that "-" is not a valid character when converting a string to DateTime.

I tried record = record.Replace("-", "/") but that ended up messing up my string and it stopped showing up (from html page).

Upvotes: 3

Views: 5565

Answers (2)

Ian
Ian

Reputation: 30813

Your problem is not with the -. There is nothing wrong with that. But you seem to use small letter m instead of capital letter M to indicate your month:

//DateTime strStartDate = DateTime.ParseExact(StartDate, "mm-dd-yyyy", CultureInfo.InvariantCulture);

(Also, note that you put it in the comment - making it less visible!)

Change it to:

//Note the capital MM
DateTime strStartDate = DateTime.ParseExact(StartDate, "MM-dd-yyyy", CultureInfo.InvariantCulture);

That's why you got the error. The small letter m is for minute, not month. To indicate month, use capital M

Upvotes: 7

Serkan Acuner
Serkan Acuner

Reputation: 190

string res = "2016030";
DateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);
 Console.WriteLine(d.ToString("MM/dd/yyyy"));

Upvotes: 1

Related Questions