Click here to Skip to main content
15,884,857 members
Please Sign up or sign in to vote.
4.33/5 (2 votes)
Hello,

I am trying to parse datetime parameter as date but I am not getting desired output, since the output is only showing year instead of the whole date.

This is my current javascript code:
JavaScript
 function drawVisualization(dataValues, chartTitle, columnNames, categoryCaption) {
    if (dataValues.length < 1)
        return;

    var data = new google.visualization.DataTable();
    data.addColumn('string', columnNames.split(',')[0]);
    data.addColumn('number', columnNames.split(',')[1]);
    data.addColumn('string', columnNames.split(',')[2]);
    data.addColumn('datetime', columnNames.split(',')[3]);

    for (var i = 0; i < dataValues.length; i++) {

        //var dateTimeString = "\/Date(1358294400000)\/";
        //var dateTime = new Date(parseInt(dateTimeString.split("/"[\(\)]/)[3]));

        var date = new Date(parseInt(dataValues[i].Date.substr(6),10));

        //date = date.getFullYear() + "-" +
        //("0" + (date.getMonth() + 1)).slice(-2) + "-" +

        data.addRow([dataValues[i].ColumnName, dataValues[i].Value, dataValues[i].Type, date]);
    }

    // Define a Pie chart
    var pie = new google.visualization.ChartWrapper({
        'chartType': 'LineChart',
        'containerId': 'PieChartContainer',
        'options': {
            'width': 950,
            'height': 450,
            'legend': 'right',
            'title': chartTitle,
            'chartArea': { 'left': 100, 'top': 100, 'right': 0, 'bottom': 100 },
            'pieSliceText': 'label',
            'tooltip': { 'text': 'percentage' }
        },
        'view': { 'columns': [3, 1] }
    });

    new google.visualization.Dashboard(document.getElementById('PieChartExample')).bind([categoryPicker, stringFilter], [pie]).draw(data);
}
    }


From the code behind, I am passing the datetime from the server as part of web method:
C#
protected void Page_Load(object sender, EventArgs e)
  {

      JavaScriptSerializer jss = new JavaScriptSerializer();

      ClientScript.RegisterStartupScript(this.GetType(), "TestInitPageScript",
      string.Format("<script type=\"text/javascript\">google.load('visualization','1.0',{{'packages':['corechart','controls']}});google.setOnLoadCallback(function(){{drawVisualization({0},'{1}','{2}','{3}');}});</script>",
      jss.Serialize(GetData()),
      "Text Example",
      "Text Example",
       "type,"));

  }

  [WebMethod]
  public static List<test> GetData()
  {
      SqlConnection conn = new SqlConnection("######");
      DataSet ds = new DataSet();
      DataTable dt = new DataTable();
      conn.Open();
      var yesterday = DateTime.Today.AddDays(-1);
      string cmdstr = "select top 5 Name, [Decimal price],Cover, UploadDate from [dbo].[database]";
      SqlCommand cmd = new SqlCommand(cmdstr, conn);
      SqlDataAdapter adp = new SqlDataAdapter(cmd);
      adp.Fill(ds);
      dt = ds.Tables[0];
      List<test> dataList = new List<test>();
      string cat = "";
      float val = 0;
      string typ = "";
      DateTime dat = DateTime.Now;

      //dat = DateTime.ParseExact("yyyyMMddHHmmss", CultureInfo.InvariantCulture);

      foreach (DataRow dr in dt.Rows)
      {
          try
          {
              cat = dr[0].ToString();

              val = Convert.ToInt32(dr[1]);

              typ = dr[2].ToString();

              dat = (DateTime)(dr[3]);

          }
          catch
          {
          }
          dataList.Add(new test(cat, val, typ, dat));
      }
      return dataList;
  }


Updated date code:

JavaScript
function drawVisualization(dataValues, chartTitle, columnNames, categoryCaption) {
        if (dataValues.length < 1)
            return;
        var data = new google.visualization.DataTable();
        data.addColumn('string', columnNames.split(',')[0]);
        data.addColumn('number', columnNames.split(',')[1]);
        data.addColumn('string', columnNames.split(',')[2]);
        data.addColumn('datetime', columnNames.split(',')[3]);

        for (var i = 0; i < dataValues.length; i++) {

            //var dateTimeString = "\/Date(1358294400000)\/";
            //var dateTime = new Date(parseInt(dateTimeString.split("/"[\(\)]/)[3]));

            //var date = new Date(parseInt(dataValues[i].Date.substr(6), 10));

            //alert(dataValues[i].Date);

            var dateString = dataValues[i].Date.substr(6);
            var currentTime = new Date(parseInt(dateString));
            var month = currentTime.getMonth() + 1;
            var day = currentTime.getDate();
            var year = currentTime.getFullYear();
            var date = day + "/" + month + "/" + year;
            alert(date);

            data.addRow([dataValues[i].ColumnName, dataValues[i].Value, dataValues[i].Type, date]);
            
        }

Any help would be very much appreciated. Many thanks in advance.
Posted
Updated 5-Mar-14 4:17am
v4
Comments
Trajan McGill 4-Mar-14 11:21am    
It would be helpful to know exactly how the dataList is being output. I assume there must be ASP.NET code that uses this dataList as a data source. Since that step of the process could well include formatting the output, it would be necessary to see that as well. Or, at least an example of a few lines of HTML output that the JavaScript is reading from. There are three places your problem could be arising: 1) the output is not formatted well to be parsed by the JavaScript; 2) the JavaScript isn't parsing the right thing or isn't parsing it the way you expect; or 3) the date is in fact being fully parsed but that google.visualization.DataTable object, whatever it is, is only showing the year portion and you need to mess around with configuring that to display the whole date and time.
miss786 4-Mar-14 11:39am    
Hi, Thank you so much for your detailed response. I updated my post with datasource to the datalist, as requested. I think it maybe a format issue, as the other data point is not matching up with the date's years, which are showing up as 2014,2015,2016..etc on the chart. I will keep trying here on my end, but any suggestion or help would be very helpful. Many thanks.
Trajan McGill 4-Mar-14 16:40pm    
Sorry, wasn't looking closely enough before and failed to notice this was a web method.

Here's where we should really look. This line:
var date = new Date(parseInt(dataValues[i].Date.substr(6),10));

Can you do an alert box or something right there, something like:
alert(dataValues[i].Date);

That would tell us what the JavaScript is attempting (and failing) to parse properly.
miss786 5-Mar-14 10:15am    
Hi, Thank you so much for your response and help. I added in alert function, was able to find the code was not parsing json datetime into date. I tried updating my code and manage to get the date to parse into readable format (please see the above updated code), but I am currently experiencing this new issue -- Uncaught Error: Type mismatch. Value 16/1/2013 does not match type datetime in column index 3 -- error and getting blank screen on the client-end. Any advice would be helpful. Many thanks.
Trajan McGill 20-Mar-14 11:28am    
What is the data type of that column in the database? You are trying to cast dr[3] into a DateTime, but perhaps you need to parse it into a DateTime instead.

Have a look here: DateTime Structure[^]

DateTime is always date and time of day. You should store date as a datetime data type, but you are able to display it in custom format: Custom Date and Time Format Strings[^].
On SQL Server side, you can 'reject' time part, using CONVERT[^] function.
 
Share this answer
 
try this...

var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));
JavaScript

 
Share this answer
 
try this...

string dt = System.DateTime.ParseExact("Date", "dd/MM/yyyy", null).ToString();
 
Share this answer
 
Comments
miss786 6-Mar-14 5:27am    
Thank you so much for your help and response. I am trying to convert the datetime into date type instead of converting into string type. Is their way to do this in the [web method] code? This what I have so far and the current code is giving me compiling errors:

DateTime dat = DateTime.Now;
//DateTime dat = new DateTime();

//dat = DateTime.ParseExact("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
//var dtt = dat.ToShortDateString();
var dtt = DateTime.ParseExact(dat, "dd/MM/yyyy", null);

foreach (DataRow dr in dt.Rows)
{
try
{
cat = dr[0].ToString();

val = Convert.ToInt32(dr[1]);

typ = dr[2].ToString();

//dat = (DateTime)(dr[3]);
dtt = (Date)(dr[3]);
//dtt = dr[3].ToString();

}

Many thanks for your help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900