Sending DateTime to jQuery Ajax in JSON format in ASP.Net

You want to send DateTime from code behind to client using jQuery AJAX.

There is a little problem here.

DateTime is a .Net structure whereas jQuery/javascript does not have any idea about it.

DateTime is .Net structure which has the value of number of ticks(100 nanoseconds) since 1st Jan 0001 mightnight AD. As this is a .Net structure, only ASP.Net understands this DateTime structure and jQuery/Javascript has no idea about the same.

You have Date object to represent the Date in javascript. It has the value of number of milliseconds since 1st Jan 1970 midnight.

So we have couple of options to send DateTime value to jQuery/javascript

  1. Convert the DateTime value of .Net to Date value of javascript in code-behind itself and send it to front end so that jQuery can make use of it.
  2. Send all the details of DateTime(day,month,year etc..) from code behind and send it to front end so that jQuery/Javascript can construct the Date object out of these details.

DateTime Jquery JSON

 

We will discuss about each of these options in detail below.

1. Convert the DateTime value of .Net to Date value of javascript in code-behind itself and send it to front end:

In the below method, we are converting DateTime of .Net(Today’s value) to Javascript’s Date object.


[System.Web.Services.WebMethod]
public static UInt64 GetDateTime()
{
  UInt64 msDiff = 0;
  try
  {
    System.DateTime dtToday = System.DateTime.Today;
    System.DateTime dtJSStart = new System.DateTime(1970, 1, 1);
    //Convert DateTime of .Net to Javascript's Date object
    //Find the difference between today's date to 1st Jan 1970 in milliseconds
    msDiff = Convert.ToUInt64(dtToday.Subtract(dtJSStart).TotalMilliseconds);
  }
  catch (Exception ex)
  {
    throw ex;
  }
  return msDiff;
}

In front end, we can call this method and consume the value and create Date object with that value.

var dt = new Date(response.d);

AJAX function code:

<script type="text/javascript">
function callAjaxMethod(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "DateTime.aspx/GetDateTimeCSharp",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dt = new Date(response.d);
$('#<%=txtDateTime.ClientID%>').val(dt.toDateString());
},
failure: function (response) {
$('#<%=txtDateTime.ClientID%>').val("Error in calling Ajax:" + response.d);
}

});

}
</script>

2. Send all the details of DateTime(day,month,year etc..) from code behind and send it to front end

[System.Web.Services.WebMethod]
public static CSharpDateTime GetDateTimeCSharp()
{
  //This .Net object would be serialized as JSON object and sent to Javascript
  CSharpDateTime dt = new CSharpDateTime();
  try
  {
    System.DateTime dtToday = System.DateTime.Today;
    dt.day = dtToday.Day;
    dt.month = dtToday.Month;
    dt.year = dtToday.Year;
    dt.hours = dtToday.Hour;
    dt.minutes = dtToday.Minute;
    dt.seconds = dtToday.Second;
    dt.milliSeonds = dtToday.Millisecond;
  }
  catch (Exception ex)
  {
    throw ex;
  }
  return dt;
}

You can use object to construct the Javascript’s Date object with the details in the front end.

var dt = new Date(response.d.year, response.d.month, response.d.day, response.d.hours, response.d.minutes, response.d.seconds, response.d.milliSeonds);

AJAX function code:


function callAjaxMethod(e) {
  e.preventDefault();
  $.ajax({
  type: "POST",
  url: "DateTime.aspx/GetDateTimeCSharp",
  data: '',
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (response) {
  var dt = new Date(response.d.year, response.d.month, response.d.day, response.d.hours, response.d.minutes, response.d.seconds, response.d.milliSeonds);
  $('#<%=txtDateTime.ClientID%>').val(dt.toDateString());
  },
  failure: function (response) {
    $('#<%=txtDateTime.ClientID%>').val("Error in calling Ajax:" + response.d);
  }
});
}

Complete Code:

Complete code of Javascript,Code-behind and Javascript is pasted below.

Code Behind:

[System.Web.Services.WebMethod]
  public static UInt64 GetDateTime()
  {
    UInt64 msDiff = 0;
    try
    {
      System.DateTime dtToday = System.DateTime.Today;
      System.DateTime dtJSStart = new System.DateTime(1970, 1, 1);
      //Convert DateTime of .Net to Javascript's Date object
      //Find the difference between today's date to 1st Jan 1970 in milliseconds
      msDiff = Convert.ToUInt64(dtToday.Subtract(dtJSStart).TotalMilliseconds);
    }
    catch (Exception ex)
    {
      throw ex;
    }
    return msDiff;
  }

[System.Web.Services.WebMethod]
public static CSharpDateTime GetDateTimeCSharp()
{
  //This .Net object would be serialized as JSON object and sent to Javascript
  CSharpDateTime dt = new CSharpDateTime();
  try
  {
    System.DateTime dtToday = System.DateTime.Today;
    dt.day = dtToday.Day;
    dt.month = dtToday.Month;
    dt.year = dtToday.Year;
    dt.hours = dtToday.Hour;
    dt.minutes = dtToday.Minute;
    dt.seconds = dtToday.Second;
    dt.milliSeonds = dtToday.Millisecond;
  }
  catch (Exception ex)
  {
    throw ex;
  }
  return dt;
}

Javascript Code:

function callAjaxMethod(e) {
  e.preventDefault();
  $.ajax({
  type: "POST",
  url: "DateTime.aspx/GetDateTimeCSharp",
  data: '',
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (response) {
  //DateTime.aspx/GetDateTime
  //var dt = new Date(response.d);
  //$('#<%=txtDateTime.ClientID%>').val(dt.toDateString());
  var dt = new Date(response.d.year, response.d.month, response.d.day, response.d.hours, response.d.minutes, response.d.seconds, response.d.milliSeonds);
  $('#<%=txtDateTime.ClientID%>').val(dt.toDateString());
  },
  failure: function (response) {
    $('#<%=txtDateTime.ClientID%>').val("Error in calling Ajax:" + response.d);
  }
});
}

ASPX Markup:

<form id="form1" runat="server">
  <div>
    <asp:TextBox ID="txtDateTime" runat="server"></asp:TextBox>
    <asp:Button ID="btnGetDateTime" runat="server" Text="Get DateTime" OnClientClick="callAjaxMethod(event)" />
  </div>
</form>

Thanks for reading the article. If you like this article, please subscribe.

 


Posted

in

,

by

Tags: