JSON.NET: Get Specific JSON Date Value

后端 未结 3 1108
无人共我
无人共我 2020-12-12 04:27

In my VB.NET project, using JSON.NET, I\'ve got a JSON from a Web API that has a value representing a date in the yyyy-MM-ddTHH:mm:ss format, and I\'d like to s

3条回答
  •  無奈伤痛
    2020-12-12 04:58

    When you get the parsed date-string from JSON.NET it will be in your culture's format as shown in your code comment:

    Dim temp As String = myJsonResult("REQ_DATE")
    ' temp = "1/17/2016 12:27:57 PM"
    

    That format is "M/d/yyyy HH:mm:ss tt" so use that format for parsing. But since it is in a format for your culture, you can let DateTime check/use all the known formats using TryParse:

    Dim dt As DateTime
    Dim temp As String = jobj("REQ_DATE").ToString
    
    If DateTime.TryParse(temp, dt) Then
        'dt is good to use!
        Console.WriteLine(dt.ToString)
        ' Prints: 1/17/2016 12:27:57 PM
    End If
    
    Dim myDesiredResult As String = dt.ToString("yyyy-MM-ddTHH:mm:ss")
    ' result: "2016-01-17T12:27:57"
    

    If you want to specify the format (it would be better to use TryParseExact):

    dt = DateTime.ParseExact(temp, "M/d/yyyy HH:mm:ss tt",
             CultureInfo.InvariantCulture)
    Console.WriteLine(dt.ToString())
    ' Also prints: 1/17/2016 12:27:57 PM
    

    Dates dont have a format, so it cant change, but it may display differently for your culture settings. You can display it any way you want, it is still the same date:

    Console.WriteLine(dt.ToString("HH yyyy MM mm dd"))
    Console.WriteLine(dt.ToString("yyyy-MM-ddTHH:mm:ss"))
    Console.WriteLine(dt.ToString("MM/d/yyyy HH:mm:ss tt"))
    

提交回复
热议问题