How to convert Javascript datetime to C# datetime?

C#Javascript.NetDatetime

C# Problem Overview


I have been reading that if you want to convert from JavaScript dates to C# dates you should use getTime() and then add that result to a C# DateTime.

Suppose I have this JavaScript time:

Date {Tue Jul 12 2011 16:00:00 GMT-0700 (Pacific Daylight Time)}

It renders to 1310522400000 milliseconds

var a = new DateTime(1970, 01, 01).AddMilliseconds(1310522400000);

// result
7/13/2011 2:00:00 AM

So this is wrong. I am not sure what I need to do.

C# Solutions


Solution 1 - C#

You could use the toJSON() JavaScript method, it converts a JavaScript DateTime to what C# can recognise as a DateTime.

The JavaScript code looks like this

var date = new Date();
date.toJSON(); // this is the JavaScript date as a c# DateTime

Note: The result will be in UTC time

Solution 2 - C#

First create a string in your required format using the following functions in JavaScript

var date = new Date();
var day = date.getDate();       // yields date
var month = date.getMonth() + 1;    // yields month (add one as '.getMonth()' is zero indexed)
var year = date.getFullYear();  // yields year
var hour = date.getHours();     // yields hours 
var minute = date.getMinutes(); // yields minutes
var second = date.getSeconds(); // yields seconds

// After this construct a string with the above results as below
var time = day + "/" + month + "/" + year + " " + hour + ':' + minute + ':' + second; 

Pass this string to codebehind function and accept it as a string parameter.Use the DateTime.ParseExact() in codebehind to convert this string to DateTime as follows,

DateTime.ParseExact(YourString, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

Hope this helps...

Solution 3 - C#

You were almost right, there's just need one little fix to be made:

var a = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds(1310522400000)
    .ToLocalTime();

Solution 4 - C#

If you want to send dates to C# from JS that is actually quite simple - if sending UTC dates is acceptable.

var date = new Date("Tue Jul 12 2011 16:00:00 GMT-0700");
var dateStrToSendToServer = date.toISOString();

... send to C# side ...

var success = DateTimeOffset.TryParse(jsISOStr, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var result);

C# DateTime already understands ISO date formats and will parse it just fine.

To format from C# to JS just use DateTime.UtcNow.ToString("o").

Personally, I'm never comfortable relying on math and logic between different environments to get the milliseconds/ticks to show the EXACT same date and time a user may see on the client (especially where it matters). I would do the same when transferring currency as well (use strings instead to be safe, or separate dollars and cents between two different integers). Sending the date/time as separate values would be just a good (see accepted answer).

Solution 5 - C#

DateTime.Parse is a much better bet. JS dates and C# dates do not start from the same root.

Sample:

DateTime dt = DateTime.ParseExact("Tue Jul 12 2011 16:00:00 GMT-0700",
                                  "ddd MMM d yyyy HH:mm:ss tt zzz",
                                  CultureInfo.InvariantCulture);

Solution 6 - C#

Since I'm in a different timezone, my JavaScript and C# end up having 2 hours difference between the same date (even when I tried to send the date to a webservice as a date [not converted to string/another object]).

I tried to use the getTime() in JavaScript and add the milliseconds to a C# date (starting on 1970-01-01) but I've always ended up with two hours in advance on my C# date.

To grant that I would get the same Date and Hour in both sides I ended up doing this:

In JavaScript I've used the UTC function:

var jsDate = Date.UTC(year,month,day,hours,minutes,seconds,millisec);

And in C# to get the correct DateTime I did this:

var date = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(jsDate);

Hope it helps someone.

Solution 7 - C#

If you are using moment.js in your application.

var x= moment(new Date()).format('DD/MM/YYYY hh:mm:ss')

Pass x to codebehind function and accept it as a string parameter. Use the DateTime.ParseExact() in c# to convert this string to DateTime as follows,

DateTime.ParseExact(YourString, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

Solution 8 - C#

UPDATE: From .NET Version 4.6 use the FromUnixTimeMilliseconds method of the DateTimeOffset structure instead:

DateTimeOffset.FromUnixTimeMilliseconds(1310522400000).DateTime

Solution 9 - C#

If you are in the U.S. Pacific time zone, then the epoch for you is 4 p.m. on December 31, 1969. You added the milliseconds since the epoch to

new DateTime(1970, 01, 01)

which, since it did not have a timezone, was interpreted as being in your timezone.

There is nothing really wrong with thinking of instants in time as milliseconds since the epoch but understand the epoch is only 1970-01-01T00:00:00Z.

You can't think of instants in times, when represented as dates, without timezones.

Solution 10 - C#

I think you can use the TimeZoneInfo....to convert the datetime....

    static void Main(string[] args)
    {
        long time = 1310522400000;
        DateTime dt_1970 = new DateTime(1970, 1, 1);
        long tricks_1970 = dt_1970.Ticks;
        long time_tricks = tricks_1970 + time * 10000;
        DateTime dt = new DateTime(time_tricks);

        Console.WriteLine(dt.ToShortDateString()); // result : 7/13
        dt = TimeZoneInfo.ConvertTimeToUtc(dt);

        Console.WriteLine(dt.ToShortDateString());  // result : 7/12
        Console.Read();
    }

Solution 11 - C#

JavaScript (HTML5)
function TimeHelper_GetDateAndFormat() {
    var date = new Date();

    return MakeValid(date.getDate()).concat(
        HtmlConstants_FRONT_SLASH,
        MakeValid(date.getMonth() + 1),
        HtmlConstants_FRONT_SLASH,
        MakeValid(date.getFullYear()),
        HtmlConstants_SPACE,
        MakeValid(date.getHours()),
        HtmlConstants_COLON,
        MakeValid(date.getMinutes()),
        HtmlConstants_COLON,
        MakeValid(date.getSeconds()));
}

function MakeValid(timeRegion) {
    return timeRegion !== undefined && timeRegion < 10 ? ("0" + timeRegion).toString() : timeRegion.toString();
}
C#
private const string DATE_FORMAT = "dd/MM/yyyy HH:mm:ss";

public DateTime? JavaScriptDateParse(string dateString)
{
    DateTime date;
    return DateTime.TryParseExact(dateString, DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None, out date) ? date : null;
}

Solution 12 - C#

There were some mistakes in harun's answer which are corrected below:

  1. date where harun used getDay() which is incorrect should be getDate()

  2. getMonth() gives one less month than actual month, So we should increment it by 1 as shown below

    var date = new Date(); var day = date.getDate(); // yields var month = date.getMonth() + 1; // yields month var year = date.getFullYear(); // yields year var hour = date.getHours(); // yields hours var minute = date.getMinutes(); // yields minutes var second = date.getSeconds(); // yields seconds

    // After this construct a string with the above results as below var time = day + "/" + month + "/" + year + " " + hour + ':' + minute + ':' + second;

Pass this string to codebehind function and accept it as a string parameter.Use the DateTime.ParseExact() in codebehind to convert this string to DateTime as follows,

DateTime.ParseExact(YourString, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

This Worked for me! Hope this help you too.

Solution 13 - C#

JS:

 function createDateObj(date) {
            var day = date.getDate();           // yields 
            var month = date.getMonth();    // yields month
            var year = date.getFullYear();      // yields year
            var hour = date.getHours();         // yields hours 
            var minute = date.getMinutes();     // yields minutes
            var second = date.getSeconds();     // yields seconds
            var millisec = date.getMilliseconds();
            var jsDate = Date.UTC(year, month, day, hour, minute, second, millisec);
            return jsDate;
        }

JS:

var oRequirementEval = new Object();
var date = new Date($("#dueDate").val());

CS:

requirementEvaluations.DeadLine = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds(Convert.ToDouble( arrayUpdateRequirementEvaluationData["DeadLine"]))
    .ToLocalTime();

Solution 14 - C#

You can also send Js time to C# with Moment.js Library :

JavaScript : var dateString = moment(new Date()).format('LLLL')

C# : DateTime.Parse(dateString);

Solution 15 - C#

var date = new Date(this.newItemDate).toDateString();

this line of code works for me

Solution 16 - C#

Newtonsoft.Json.JsonConvert.SerializeObject(Convert.ToDateTime(dr[col.ColumnName])).Replace('"', ' ').Trim();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionchobo2View Question on Stackoverflow
Solution 1 - C#GarthView Answer on Stackoverflow
Solution 2 - C#HarunView Answer on Stackoverflow
Solution 3 - C#vasiliyView Answer on Stackoverflow
Solution 4 - C#James WilkinsView Answer on Stackoverflow
Solution 5 - C#MrchiefView Answer on Stackoverflow
Solution 6 - C#Rafael MerlinView Answer on Stackoverflow
Solution 7 - C#ragaView Answer on Stackoverflow
Solution 8 - C#Andriy TolstoyView Answer on Stackoverflow
Solution 9 - C#Ray ToalView Answer on Stackoverflow
Solution 10 - C#shenhengbinView Answer on Stackoverflow
Solution 11 - C#MyKuLLSKIView Answer on Stackoverflow
Solution 12 - C#Rohit AroraView Answer on Stackoverflow
Solution 13 - C#Jaydeep ShilView Answer on Stackoverflow
Solution 14 - C#AminSojoudiView Answer on Stackoverflow
Solution 15 - C#HamedView Answer on Stackoverflow
Solution 16 - C#Sayed AzharuddinView Answer on Stackoverflow