javascript - 在客户端将 C# DateTime 转换为 LocalTime (JS)

标签 javascript c# datetime

在服务器上我使用 Yahoo API 来获取货币 http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=USDGBP=X,USDEUR=X

在结果中,我得到了 DateTime 并希望将其转换为 DateTime 对象,以便稍后将其转换为 Local为客户服务的时间

我用以下方法做到了

DateTime d = dateOnly.Add(timeOnly.TimeOfDay);

我现在想将其转换为客户端上的本地时间(Javascript)

我在客户端尝试过

var d = new Date(d + " UTC");
alert(d.toString());

编辑d值为2015-04-06T12:32:00

但出现错误无效日期

最佳答案

只需更改您的代码即可正确形成 ISO 8601 字符串。

var d = new Date(d + "Z");

Chrome 调试控制台的屏幕截图:

Screenshot

或者,您可以通过确保设置 DateTime 值的 .Kind 来确保 Z 是由 .NET 代码添加的到 DateTimeKind.Utc

例如:

d = DateTime.SpecifyKind(d, DateTimeKind.Utc);

或者更好的是,您可以直接将其解析为 UTC。

string dateOnly = "4/6/2015";
string timeOnly = "11:32pm";

DateTime dt = DateTime.ParseExact(dateOnly + " " + timeOnly,
    "M/d/yyyy h:mmtt",
    CultureInfo.InvariantCulture,
    DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);

这可能是最安全的方法。现在类型已经是 UTC,并且 Z 已经就位。

关于javascript - 在客户端将 C# DateTime 转换为 LocalTime (JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29470290/

相关文章:

javascript - 在 jQuery UI 中触发鼠标拖动

c# - 为层次结构中的实体获取父级

java - 将具有自定义时区的 java.util.Date 转换为 UTC

javascript - 仅使用年(没有月或日)与谷歌时间线图表

c# - Task.ContinueWith(..., TaskScheduler.FromCurrentSynchronizationContext()) *不* 在 UI 线程上运行的任何场景?

wpf - DateTime 未在 Datagrid、ListView 中以当前区域性格式显示

javascript - 使用javascript选择div文本的选择位置

javascript - 使现有的不可写和不可配置的属性可写和可配置

javascript - 隔离函数范围不起作用

C# 系统.FormatException : Input string was not in a correct format