Put date in American format with substring

4

How to put the string 22012018 which is a date in the American format to save to the database? The code below returns me the value:

  

2018-22-01

That is, YEAR-DAY-MONTH

The right one would be MONDAY-DAY

 EstFData = Path.GetFileName(arquivo).Substring(4, 8).Trim();
 EstFData = EstFData.Substring(4, 4) + "-" + EstFData.Substring(3, 2) + "-" + EstFData.Substring(0, 2);
    
asked by anonymous 16.03.2018 / 17:37

3 answers

4

If you prefer to use less verbose code, you can try this way:

EstData = DateTime.ParseExact(
        EstData, 
        "ddMMyyyy", 
        System.Globalization.CultureInfo.CurrentCulture)
    .ToString("yyyy-MM-dd");
    
16.03.2018 / 17:45
1

I think the way you typed is correct, only the position is incorrect, try this:

EstFData = EstFData.Substring(3, 4) + "-" + EstFData.Substring(2, 2) + "-" + EstFData.Substring(0, 2);
    
16.03.2018 / 17:43
0

Use the DateTime.ParseExact method to convert to datetime. Here's an example:

DateTime dataConvertida = DateTime.ParseExact("22012018", "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);

To get this date in your code, I understand it would look like this:

string EstFData = Path.GetFileName(arquivo).Substring(4, 8).Trim();
DateTime dataConvertida = DateTime.ParseExact(EstFData, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);
    
16.03.2018 / 17:50