Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datetime

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).

like image 636
Havoux Avatar asked Jan 01 '26 03:01

Havoux


1 Answers

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

like image 112
Ian Avatar answered Jan 03 '26 16:01

Ian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!