locked
JSON Serialize date time format RRS feed

  • Question

  • User-1104215994 posted

    Hi,

    I am trying to format JSON response date-time from my web API. I would like to remove the milliseconds from date-time. How can I do it?

    var resultResponse = JsonConvert.SerializeObject(gameConfirmResponse, Formatting.Indented,
                    new JsonSerializerSettings
                    {
                        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
                        DateTimeZoneHandling = DateTimeZoneHandling.Local
                    });
                response = new HttpResponseMessage
                {
                    StatusCode = System.Net.HttpStatusCode.OK,
                    Content = new StringContent(resultResponse, System.Text.Encoding.UTF8, "application/json"),
                };
    gameConfirmResponse.purchaseStatusDate = DateTime.Now;
    gameConfirmResponse.coupons = new List<Coupon>();
    
    var gameCouponResult = new Coupon()
    {
        expiryDate = DateTime.Now.AddDays(90),
        Pin = (string)jsonResult.SelectToken("ePin"),
        Serial = (string)jsonResult.SelectToken("password")
    };

    Here is the JSON response:

    {
        
        "unitPrice": 5.0,
        "totalPrice": 5.0,
        "purchaseStatusDate": "2019-10-23T11:49:55.9401433+03:00",
        "coupons": [
            {
                "expiryDate": "2020-01-21T11:49:55.9401433+03:00",
                "Serial": "234567",
                "Pin": "YSUDJJFKFK"
            }
        ]
    }

    Wednesday, October 23, 2019 8:57 AM

Answers

  • User-474980206 posted

    Either convert the date time properties to strings and format or use a custom date formater (see json.net documentation). 

    note: your current dates also have timezone offset so it will e the the proper time in the browser timezone.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 23, 2019 9:14 AM

All replies

  • User-474980206 posted

    Either convert the date time properties to strings and format or use a custom date formater (see json.net documentation). 

    note: your current dates also have timezone offset so it will e the the proper time in the browser timezone.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 23, 2019 9:14 AM
  • User-1104215994 posted

    Adding this solved my problem.

    DateFormatString = "yyyy-MM-ddThh:mm:ss"

    Wednesday, October 23, 2019 9:31 AM