Well I am trying to convert System's current date and time into integer value and then adding it into List.
The code is
List<int> _data = new List<int>();
foreach (DataRow row in dt.Rows)
{
_data.Add((int)Convert.ToInt32(DateTime.Now.ToLocalTime()));
_data.Add((int)Convert.ToInt32(row["S11"]));
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData = jss.Serialize(_data);
Response.Write(chartData);
I am getting error which says Invalid cast from "DateTime' to 'Int32'
I want to convert in such form to make the json which look like[1386216561000,74] Here the first member is time in integer format and second is the data which is coming from sql server.
Actually what I am trying to do is something similar to this php code.
The code is
<?php
// Set the JSON header
header("Content-type: text/json");
$x = time() * 1000;
// The y value is a random number
$y = rand(0, 100);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
You need to convert your time to Epoch time or to some timespan value from a certain reference point.
Here is the code how you calculate a epoch time:
var timeDiff=DateTime.UtcNow - new DateTime(1970, 1, 1);
var totaltime = timeDiff.TotalMilliseconds;
The PHP time() function returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
So to mimic this functionality in C#, try this:
private static double GetUnixEpoch(this DateTime dateTime)
{
var unixTime = dateTime.ToUniversalTime() -
new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return unixTime.TotalSeconds;
}
Usage:
var unixTime1 = DateTime.Now.GetUnixEpoch();
Note:
GetUnixEpochreturns adouble.
So your code should read like this:
List<double> _data = new List<double>();
foreach (DataRow row in dt.Rows)
{
_data.Add(DateTime.Now.GetUnixEpoch());
_data.Add((double)Convert.ToDouble(row["S11"]));
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData = jss.Serialize(_data);
Response.Write(chartData);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With