Вопрос

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: 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);

DateTime cannot be implicitly converted to int. Consider using ToString() with format. For example...

_data.Add((int)Convert.ToInt32(DateTime.Now.ToLocalTime().ToString("HHmmssfff"));

Good Luck!

You can convert your date into UnixTime Stamp :

Convert Date Into UnixTimeStamp :

public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
    return (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
}

Converta UnitTimeStamp to Date :

public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
    // Unix timestamp is seconds past epoch
    System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0);
    dtDateTime = dtDateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
    return dtDateTime;
}
 var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
 Console.WriteLine ( Convert.ToInt64((DateTime.UtcNow - epoch).TotalSeconds));;

Epoch time starts on 1 Jan 1970, we get the current UTC time and subtract the date Epoch time starts from, we then convert the value to the total number of seconds that has passed since Epoch time.

Additionally, we convert the value to Int64, as Int32 will no longer be able to store the total number of seconds once we reach 2038.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top