73

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.

Tija
  • 1,691
  • 4
  • 20
  • 33

7 Answers7

97

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());
}
rnofenko
  • 9,198
  • 2
  • 46
  • 56
  • 3
    toISOString() is doing more not mentioned here. I converts the JS date to a utc date from 4th february 2018 it converts to 3th february 2018 2300Z and on server side I get then: 03/02/2018 23:00:00 so I have to do: myDate.ToLocalTime() (assumed current culture is DE) then I got 04.02.2018. – Pascal Feb 15 '18 at 20:17
  • I correct: "...on server side I get then: 03/02/2018 22:00:00" – Pascal Feb 15 '18 at 21:18
37

The following format should work:

$.ajax({
    type: "POST",
    url: "@Url.Action("refresh", "group")",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ 
        myDate: '2011-04-02 17:15:45'
    }),
    success: function (result) {
        //do something
    },
    error: function (req, status, error) {
        //error                        
    }
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • this would assume the browser/clients time and the server time are in sync, which wouldn't necessarily be the case. – Tija Apr 02 '11 at 16:32
  • 2
    @amonteiro, of course, you could always convert the data in universal time before sending so that on the server you could convert back to server local time. – Darin Dimitrov Apr 02 '11 at 16:33
  • This worked great. How do I send a date that's NOT the second of April though, maybe a Date variable? – sanepete Oct 09 '17 at 16:03
  • @sanepete I believe that you can provide any properly formatted date string or variable containing the date string and it will work. – Owen Oct 30 '17 at 16:26
  • @Owen, yes thanks, I ended up using something similar to: data: JSON.stringify({ myDate: myAwesomeDate }), – sanepete Oct 31 '17 at 15:41
8

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                        
           }
       });
Kamran
  • 371
  • 1
  • 4
  • 15
0

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

John Zumbrum
  • 2,786
  • 8
  • 36
  • 60
0

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();
santosh singh
  • 27,666
  • 26
  • 83
  • 129
  • so DateTime.Now.ToUniversalTime().AddMinutes(double.Parse(MyDate)).ToString(); would give me univeral time on the server right? If I do .ToLocalTime(), would it then convert that to server time? – Tija Apr 02 '11 at 16:30
  • actually now that I think of it, this would only give me the offset not the actual time being passed. so I would have to pass two variables - the offset like you posted, and the datetime like Darin posted – Tija Apr 02 '11 at 16:35
0

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");
Nanu
  • 3,010
  • 10
  • 38
  • 52
-1
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);
            }
        });