解析日期与时间从JavaScript到C# [英] Parsing Date-and-Times from JavaScript to C#

查看:119
本文介绍了解析日期与时间从JavaScript到C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想要传递给我的web服务的一些JavaScript代码。我的JavaScript代码应该在UTC格式发送日期。在当地,我产生我的代码在当时是在下午12时30分43秒。当我执行我的JavaScript代码,生成以下日期/时间:

I have some JavaScript code that I'm trying to pass to my web service. My JavaScript code is supposed to send a date in UTC format. Locally, the time that I generated my code at was at 12:30:43 pm. When I executed my JavaScript code, the following date/time was generated:

2012-06-03T20:30:43.000Z

这日期/时间从这段代码生成的:现在

That date/time was generated from this code:

var now = new Date();
var utcDate = new Date(
  now.getUTCFullYear(),
  now.getUTCMonth(),
  now.getUTCDate(),
  now.getUTCHours(),
  now.getUTCMinutes(),
  now.getUTCSeconds()
);

当我从Javascript传递的日期/时间回到我的Web服务,它被序列如下所示

When I pass the date/time from JavaScript back to my web service, it is serialized as shown here:

20120603163043

这看起来是正确的我在这一点上。那么我就需要采取该字符串,并将其转换为C#中的日期/时间。在试图做到这一点,我用下面的C#代码:

That looks correct to me at this point. I then need to take that string and convert it to a date/time in C#. In an attempt to do that, I'm using the following C# code:

DateTime _value = DateTime.MinValue;
DateTime.TryParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out _value)

当发生这种情况时,我得到下面的日期/时间。
6/3/2012下午12时30分43秒

When that happens, I get the following date/time. 6/3/2012 12:30:43 PM

我在做什么错了?我期待的日期/时间是6/3/2012下午四时30分43秒。

What am I doing wrong? I was expecting the date/time to be 6/3/2012 4:30:43 PM

推荐答案

你得到的结果是正确的,但请查看 财产你的的DateTime 。你会发现它没有设置为 UTC 本地

The result you get is correct, but please check the Kind property of your DateTime. You'll notice it's not set to UTC but to Local.

您可以使用 DateTimeStyles.AdjustToUniversal 来生成一个的DateTime 设置为 UTC

You can use DateTimeStyles.AdjustToUniversal to generate a DateTime with Kind set to UTC.

DateTime dateTime;
DateTime.TryParseExact(
    value,
    "yyyyMMddHHmmss",
    CultureInfo.InvariantCulture,
    DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
    out dateTime);



看到它工作的 ideone

这篇关于解析日期与时间从JavaScript到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆