0

How can I convert a Json DateTime string to normal date format(dd.mm.yyyy)?

    public JsonResult ProductListGrid()
    {
        try
        {
            var productListModel = new List<ProductListModel>();

            var products= ProductOperations.ProductListGetirDT(ExceptionCatcher);
            foreach (var item in products)
            {
                productListModel.Add(new ProductListModel()
                {
                    //...
                    ProductDate = Convert.ToDateTime(item.ProductDate ),
                   //:::
                });
            }

            return Json(productListModel , JsonRequestBehavior.AllowGet);
        }
        ...

17.12.2018 (I expect)

/Date(1549659600000)/ (Output)

  • Does this answer your question? [How can I convert a Unix timestamp to DateTime and vice versa?](https://stackoverflow.com/questions/249760/how-can-i-convert-a-unix-timestamp-to-datetime-and-vice-versa) – Markus Deibel Nov 08 '19 at 07:40
  • I think this would answer your question https://stackoverflow.com/questions/10286204/the-right-json-date-format – Gabriel Llorico Nov 08 '19 at 07:43
  • I think your question may be the wrong way round. From the title it sounds like you're trying to deserialize a datetime from JSON, however the rest of your question reads like you're having trouble serilizing a DateTime to JSON. Please clarify. – phuzi Nov 08 '19 at 08:54

2 Answers2

0

You can try this:

time = datetime.datetime.strptime(ProductDate, '%Y-%m-%d %H:%M:%S.%f')  
Dino
  • 7,779
  • 12
  • 46
  • 85
Ananthu M
  • 77
  • 5
0

You can use TryParseExact to convert the string date to DateTime

private static DateTime ParseDate(string providedDate)
{
    DateTime validDate;
    string[] formats = { "dd.MM.yyyy" };
    var dateFormatIsValid = DateTime.TryParseExact(
        providedDate,
        formats,
        CultureInfo.InvariantCulture,
        DateTimeStyles.None,
        out validDate);
    return dateFormatIsValid ? validDate : DateTime.MinValue;
}

And call this method to parse the json date format

ProductDate = ParseDate(item.ProductDate)
Krishna Varma
  • 4,238
  • 2
  • 10
  • 25