Put date in American format with substring

Asked

Viewed 87 times

4

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

2018-22-01

I mean, YEAR-DAY-MONTH

The right one would be YEAR-MONTH-DAY

 EstFData = Path.GetFileName(arquivo).Substring(4, 8).Trim();
 EstFData = EstFData.Substring(4, 4) + "-" + EstFData.Substring(3, 2) + "-" + EstFData.Substring(0, 2);
  • 1

    One detail: to save in the bank, you can inform only the DateTime and not the string, so the bank itself takes care of the format it is working on

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");
  • 1

    I was doing it in the fiddle, but as you put it, I leave it here: =] https://dotnetfiddle.net/Zk1acB

1

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

EstFData = EstFData.Substring(3, 4) + "-" + EstFData.Substring(2, 2) + "-" + EstFData.Substring(0, 2);

0

Use the Datetime.Parseexact method to convert to datetime. Following example:

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.