简体   繁体   中英

How to convert Javascript datetime to C# datetime?

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

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

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

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

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...

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

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

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

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]).

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

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

更新<\/strong>:从 .NET 4.6 版开始,改用DateTimeOffset<\/a>结构的FromUnixTimeMilliseconds<\/a>方法:

DateTimeOffset.FromUnixTimeMilliseconds(1310522400000).DateTime

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

new DateTime(1970, 01, 01)

JavaScript (HTML5) <\/h3>
 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(); }<\/code><\/pre>

C# <\/h3>
 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; }<\/code><\/pre>"

There were some mistakes in harun's answer which are corrected 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; 

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

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

我能够使用@Garth指出的解决方案来解决问题。

date.toJSON()

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();
    }
var date = new Date(this.newItemDate).toDateString();
Newtonsoft.Json.JsonConvert.SerializeObject(Convert.ToDateTime(dr[col.ColumnName])).Replace('"', ' ').Trim();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM