在ASP.NET MVC2,转换时间用户的时区。如何获得时区信息? [英] In ASP.NET MVC2, convert time user's timezone. How to get timezone info?

查看:425
本文介绍了在ASP.NET MVC2,转换时间用户的时区。如何获得时区信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的datetime存入数据库,然后我检索值..我的服务器数据库位于其他国家。所以当值检索它正在其他国家的日期和时间。

I stored datetime into database then i retrieve the values.. My server db is located other country. so when the value is retrieve it is taking other country date and time..

我试着在控制器如下,

 if (item.CreatedDate == null)
        {
            item.CreatedDate = DateTime.Now;
            var timeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(item.CreatedDate, TimeZoneInfo.Local.Id, item.CreatedDate.Value).ToString();
        }

我行错误在这里...如何纠正它吗?

I got line error here... How to correct it?

推荐答案

您正在传递一个甚至不正确的数据类型的值。阅读上 的TimeZoneInfo 所以你知道如何正确使用它。

You're passing values that aren't even of the right data type. Read up on TimeZoneInfo so you know how to use it properly.

另请阅读:

  • Why you shouldn't use DateTime.Now
  • The timezone tag wiki
  • DST and Time Zone Best Practices

也了解到,这里的某个地方,你实际上必须知道用户的时区。只需调用 TimeZoneInfo.Local.Id 是行不通的,因为这也是服务器的时区。有没有通过MVC进行了解你的用户的时区法宝。你要问他们,或者采用一些涉及的JavaScript等策略。

Also understand that somewhere here you actually have to know the user's time zone. Just calling TimeZoneInfo.Local.Id isn't going to work, because that is also the server's time zone. There's no magic performed by MVC to know the time zone of your user. You'll have to ask them for it, or employ some other strategy involving JavaScript.

从您的意见,看来你正在寻找的东西是这样的:

From your comments, it appears you are looking for something like this:

// These should be stored in UTC.  Do not store them in anyone's local time.
item.CreatedDate = DateTime.UtcNow;
item.UpdatedDate = DateTime.UtcNow;

// Then later when you want to convert to a specific time zone, do this
string timeZoneId = "India Standard Time"; // as an example
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
DateTime localCreated = TimeZoneInfo.ConvertTimeFromUtc(item.CreatedDate, timeZone);
DateTime localUpdated = TimeZoneInfo.ConvertTimeFromUtc(item.UpdatedDate, timeZone);

此外,它好像你可能会使用的DateTime?(可空的日期时间)为您的属性。它没有意义的,做这些字段。他们应该是在你的数据库非空,总是包含值。

Also, it seems like you might be using DateTime? (nullable datetimes) for your properties. It doesn't make sense to do that for these fields. They should be non-null in your database and always contain a value.

这篇关于在ASP.NET MVC2,转换时间用户的时区。如何获得时区信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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