0

I am having trouble when converting dates from json in a DateTime value that then I could insert into a database.

The problem comes because json's date format is mm/dd/yyy and Trying to convert that value to datetime works until it comes a date like "07/13/2020".

fecha = json.created_at;             
date = Convert.ToDateTime(fecha);
string finalDate = date.ToString("yyyy-MM-dd");

So I need to know how can I change format of this value, so then it can always be converted to datetime

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
victoriana
  • 69
  • 5
  • What's the problem with how Convert.ToDateTime() is formatting it? – jfiggins Feb 26 '20 at 21:08
  • I'm doing a loop over a json results, this json returns dates in mm/dd/yyy format, problem comes in "date = Convert.ToDateTime(fecha);" when the value returns something like 07/13/2020 since month "13" doesn't exists – victoriana Feb 26 '20 at 21:10
  • 5
    tip: when you want to save a `DateTime` into the database: **don't format it at all**. Use a parameter where the `.Value` is the `DateTime`; then it will be correct; that leaves the parse step - so: perhaps use `DateTime.Parse` and provide a format specifier? – Marc Gravell Feb 26 '20 at 21:11
  • @victoriana SQL should still recognize that as a date, correct? – jfiggins Feb 26 '20 at 21:11
  • @victoriana `Convert.ToDateTime(fecha)` uses `CurrentCulture` as the `IFormatProvider` by default. That means if your culture is e.g. `en-US` it will try to parse into `MM/dd/yyyy`. As Marc said, if you know what the format will be, use the `DateTime.Parse` method. – Dávid Kaya Feb 26 '20 at 21:20

2 Answers2

0

It's Simple you can define your json format while converting your json date to datetime

 fecha = json.created_at;  //"07/13/2020";
 var date = DateTime.ParseExact(fecha, "MM/dd/yyyy", 
                                           CultureInfo.InvariantCulture);

 string finalDate = date.ToString("yyyy-MM-dd");

Hammad Shabbir
  • 722
  • 1
  • 6
  • 13
0

I think DateTime.ParseExact is the method you are looking for: DateTime.ParseExact(fecha, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture) yields [7/13/2020 12:00:00 AM].

Pay attention to capital and small M in the format string, M is month, m is minute!