How do you pass a date time (i need it to the second) to c# using jquery and mvc3. This is what I have
var date = new Date();
$.ajax(
{
type: "POST",
url: "/Group/Refresh",
contentType: "application/json; charset=utf-8",
data: "{ 'MyDate': " + date.toUTCString() + " }",
success: function (result) {
//do something
},
error: function (req, status, error) {
//error
}
});
I can't figure out what format the date should be in, for C# to understand it.
This question is related to
c#
jquery
json
asp.net-mvc-3
try this
var date = new Date();
$.ajax(
{
type: "POST",
url: "/Group/Refresh",
contentType: "application/json; charset=utf-8",
data: "{ 'MyDate': " + date.getTimezoneOffset() + " }",
success: function (result) {
//do something
},
error: function (req, status, error) {
//error
}
});
In C#
DateTime.Now.ToUniversalTime().AddMinutes(double.Parse(MyDate)).ToString();
There is a toJSON()
method in javascript returns a string representation of the Date object. toJSON() is IE8+ and toISOString() is IE9+. Both results in YYYY-MM-DDTHH:mm:ss.sssZ
format.
var date = new Date();
$.ajax(
{
type: "POST",
url: "/Group/Refresh",
contentType: "application/json; charset=utf-8",
data: "{ 'MyDate': " + date.toJSON() + " }",
success: function (result) {
//do something
},
error: function (req, status, error) {
//error
}
});
Update: Please see marked answer as a better solution to implement this. The following solution is no longer required.
Converting the json date to this format "mm/dd/yyyy HH:MM:ss"
dateFormat is a jasondate format.js file found at blog.stevenlevithan.com
var _meetStartTime = dateFormat(now, "mm/dd/yyyy HH:MM:ss");
I found that I needed to wrap my datetime string like this:
"startdate": "\/Date(" + date() + ")\/"
Took me an hour to figure out how to enable the WCF service to give me back the error message which told me that XD
Try to use toISOString(). It returns string in ISO8601 format.
GET method
javascript
$.get('/example/doGet?date=' + new Date().toISOString(), function (result) {
console.log(result);
});
c#
[HttpGet]
public JsonResult DoGet(DateTime date)
{
return Json(date.ToString(), JsonRequestBehavior.AllowGet);
}
POST method
javascript
$.post('/example/do', { date: date.toISOString() }, function (result) {
console.log(result);
});
c#
[HttpPost]
public JsonResult Do(DateTime date)
{
return Json(date.ToString());
}
var Ihours = Math.floor(TotMin / 60);
var Iminutes = TotMin % 60; var TotalTime = Ihours+":"+Iminutes+':00';
$.ajax({
url: ../..,
cache: false,
type: "POST",
data: JSON.stringify({objRoot: TotalTime}) ,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
},
error: function (er) {
console.log(er);
}
});
Source: Stackoverflow.com