user1835316
user1835316

Reputation: 127

Json string array format Date Time field - yyyy-MM-dd hh:mm:ss

I have a json array string where I am getting the data from a database, I need to format the DateAndTime field in the following format: yyyy-MM-dd hh:mm:ss, it needs to be dynamic as the data that is passed through will always differ except for the DateAndTime

Below is what I've attempted so far.

ASPX

var chartData = <%= DataToJSONChart() %>;
var new_data = []   
for (var i = 0; i < chartData.length; i++) {
   var date = new Date(parseInt(chartData[i].DateAndTime.substr(6)));
   new_data.push(date);
 }
 chartData.tblGeneral = new_data;

VB

Public Function DataToJSONChart() As String
Dim dt As DataTable
Dim ds As New DataSet()
ds = ChartData(4, DateTime.Parse("2012-06-01 00:00:00"), DateTime.Parse("2012-06-10 23:59:59"))
dt = ds.Tables(0)
Dim serializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))
Dim row As Dictionary(Of String, Object)
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)
For Each col As DataColumn In dt.Columns
row.Add(col.ColumnName, dr(col))
Next
rows.Add(row)
Next
serializer.MaxJsonLength = Int32.MaxValue
Return serializer.Serialize(rows)
End Function

Upvotes: 1

Views: 2768

Answers (1)

Software Engineer
Software Engineer

Reputation: 3956

You can format DateTime by checking its column name on server side:

For Each dr As DataRow In dt.Rows
    row = New Dictionary(Of String, Object)
    For Each col As DataColumn In dt.Columns
        If col.ColumnName = "DateTimeColumnName" Then
            Dim dt As DateTime = DateTime.Parse(dr(col).ToString())
            row.Add(col.ColumnName, dt.ToString("yyyy-MM-dd hh:mm:ss"))
        Else
            row.Add(col.ColumnName, dr(col))
        End If
    Next
    rows.Add(row)
Next

Upvotes: 1

Related Questions