在ASP.NET MVC2,转换时间用户的时区。如何获得时区信息?

编程入门 行业动态 更新时间:2024-10-08 02:17:59
本文介绍了在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.

另请阅读:

  • 为什么你不应该使用 DateTime.Now
  • 时区标签维基
  • DST和时区的最佳实践
  • 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,转换时间用户的时区。如何获得时区信息?

本文发布于:2023-11-28 08:15:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641628.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时区   如何获得   时间   用户   信息

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!