简体   繁体   English

C#DateTime到Javascript DateTime

[英]C# DateTime to Javascript DateTime

I'm using the following code to pass to my javascript code 我正在使用以下代码传递给我的JavaScript代码

sb.Append("start: new Date(" + Convert.ToDateTime(appointment.AppointmentDate).Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds.ToString() + "),");

The problem is that it's not including the time along with the date. 问题在于它不包括时间和日期。 How can I include the time as well? 我也该如何计算时间?

Thanks! 谢谢!

You can parse date/time string which is in en-US format. 您可以解析en-US格式的日期/时间字符串。

Put this code in your aspx page into the SCRIPT tag and you will have your DateTime value in dt variable. 将此代码放在aspx页面中的SCRIPT标记中,您的DateTime值将在dt变量中。

var dtString = '<%= MyDateTimeObject.ToString((new System.Globalization.CultureInfo("en-US")).DateTimeFormat) %>';

var dt = new Date(dtString );

问题可能是区域设置,请尝试:

sb.Append("start: new Date(" + Convert.ToDateTime(appointment.AppointmentDate).Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "),");
using System;

class Program
{
    static void Main(string[] args)
    {
        DateTime? myTime = new DateTime(1970, 1, 1, 0, 0, 1);

        Console.Write(myTime.Value.ToUnixTimeInMs().ToString());
        Console.Read();
    }
}

public static class DateTimeExtensions
{
    private static readonly DateTime unixEpoch = new DateTime(1970, 1, 1);

    public static double ToUnixTimeInMs(this DateTime dateTime)
    {
        return dateTime.Subtract(DateTimeExtensions.unixEpoch).TotalMilliseconds;
    }
}

Simply pass the return value of ToUnixTimeInMs() into the constructor of a JavaScript Date object. 只需将ToUnixTimeInMs()的返回值传递到JavaScript Date对象的构造函数中即可。

If you have .NET 3.5+ or the AJAX Extensions for .NET 2.0 , you may already have the methods you need to convert objects to JavaScript in the JavaScriptSerializer class. 如果您具有.NET 3.5+或.NET 2.0AJAX扩展 ,则可能已经具有在JavaScriptSerializer类中将对象转换为JavaScript所需的方法。

Add a reference to System.Web.Extensions. 添加对System.Web.Extensions的引用。

using System.Web.Script.Serialization;

...

var jsSerializer = new JavaScriptSerializer();
string jsDate = jsSerializer.Serialize(appointment.AppointmentDate);

Now, on the JS side, you're going to have to undo the JSON serialization using a JSON parser . 现在,在JS端,您将不得不使用JSON解析器撤消JSON序列化。

One way is to use Date.parse that can handle many more formats. 一种方法是使用可以处理更多格式的Date.parse。

var d = new Date(Date.parse("<your date here>"));

You need to use new Date and Date.parse because Date.parse does not return a date object but number of milliseconds since 1970 nnn something. 您需要使用新的Date和Date.parse,因为Date.parse不会返回日期对象,而是自1970 nnn以来的毫秒数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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