How to convert dd/MM/yyyy HH:mm:ss to yyyy-MM-dd HH:mm:ss

Asked

Viewed 1,155 times

0

If I try to convert the date this way in Visual Studio works, but when I deploy the API (this already published) responds error 500.

string added = "10/09/2018 10:20:11";
added = DateTime.ParseExact(added, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
                .ToString("yyyy-MM-dd HH:mm:ss");

Does it have to do with the . net core?

Just remove that works again on the deploy

It stops as soon as I publish on Linux Ubuntu using apache.

I didn’t know what causes the problem but solved by doing the conversion manually as follows

private string ConverterData(string added)
{
    string datahora = added;
    var splitdatahora = datahora.Split(' ');
    string data = splitdatahora[0];
    string hora = splitdatahora[1];
    var splitdata = data.Split('/');
    var dia = splitdata[0];
    var mes = splitdata[1];
    var ano = splitdata[2];
    string novoFormato = ano + "-" + mes + "-" + dia + " " + hora;
    return novoFormato;
}
  • 2

    Is this exactly the code? Including the string? Are you sure that the string isn’t it coming from somewhere else? It looks like a lack of care with the culture...

  • 1

    Where does the variable come from added? Probably your server’s default language is set to English and this changes the default date format, so the error happens.

2 answers

2


The problem is probably because the CultureInfo on the machine where you made the deploy is different from your local machine (which should be pt-br). Try to put the following code snippet below by putting the CultureInfo as pt-br. I tested it here and it worked.

var culture = new CultureInfo("pt-BR", false);
string added = "10/09/2018 10:20:11";
added = DateTime.ParseExact(added, "dd/MM/yyyy HH:mm:ss", culture)
                            .ToString("yyyy-MM-dd HH:mm:ss");

1

I had a similar fix problem doing so:

string added = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
  • 1

    How this could help anything?

Browser other questions tagged

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