Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert System Date and time into integer

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);
?>
like image 420
SPandya Avatar asked May 01 '26 11:05

SPandya


2 Answers

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;
like image 138
Sameer Avatar answered May 03 '26 00:05

Sameer


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: GetUnixEpoch returns a double.


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);
like image 24
Karl Anderson Avatar answered May 03 '26 01:05

Karl Anderson