[c#] Pass a datetime from javascript to c# (Controller)

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

The answer is


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

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC