如何在 ASP.NET 中使用时区? [英] How to work with time zones in ASP.NET?

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

问题描述

我正在做一个在线提醒系统"项目(ASP.NET 2.0 (C#)/SQL Server 2005)

I am working on an "online reminder system" project (ASP.NET 2.0 (C#) / SQL Server 2005)

这是一项提醒服务,会在特定日期向用户发送邮件.但问题是用户并非来自特定国家/地区,而是来自世界各地和不同时区.现在,当我注册时,我询问用户时区的方式与 Windows 在安装时询问我们的时区的方式相同.

As this is a reminder service which will send the mail to users on a particular dates. But the problem is users are not from a specific countries, they are from all over the world and from different time zones. Now When I am registering I am asking for users time zone in the same way as windows asks our time zone at the time of installation.

但是我没有得到如果用户选择了 (+5.30) 或某个时区,那么如何在我的 asp.net 应用程序中处理这个时区.如何根据时区工作.

But I am not getting the if the user selected (+5.30) or something timezone then how to handle this time zone in my asp.net application. How to work according to timezone.

请建议是否有更好的方法来处理此应用程序中的时区??

And please suggest if there is any better way to handle timezones in this application ??

谢谢

推荐答案

首先要确定您的数据所在的时区.我建议确保您存储的任何 DateTime 都以 UTC 时间存储(使用DateTime.ToUniversalTime() 来掌握它.

First thing is to make sure which time zone your data is in. I would recommend making sure that any DateTime that you store, is stored in UTC time (use the DateTime.ToUniversalTime() to get hold of it).

当您要为用户存储提醒时,您将需要当前的 UTC 时间,添加或删除用户的时区差异,并将该新时间转换回 UTC;这是您想要存储在数据库中的内容.

When you are to store a reminder for a user, you will need the current UTC time, add or remove the user's time zone difference, and convert that new time back to UTC; this is what you want to store in the DB.

然后,当您要检查要发送的提醒时,您只需根据UTC时间在数据库中查找要立即发送的提醒;基本上获取所有时间戳在 DateTime.Now.ToUniversalTime() 之前的提醒.

Then, when you want to check for reminders to send, you simply need to look in the database for reminders to send out now, according to UTC time; essentially get all reminders that have a time stamp that is before DateTime.Now.ToUniversalTime().

更新一些实现细节:您可以从 TimeZoneInfo.GetSystemTimeZones() 方法中获取时区列表;您可以使用它们来显示用户的时区列表.如果您存储所选时区的 Id 属性,您可以从中创建一个 TimeZoneInfo 类实例,并计算给定本地日期/时间值的 UTC 时间:

Update with some implementation specifics: You can get a list of time zones from the TimeZoneInfo.GetSystemTimeZones() method; you can use those to show a list of time zones for the user. If you store the Id property from the selected time zone, you can create a TimeZoneInfo class instance from it, and calculate the UTC time for a given local date/time value:

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("<the time zone id>");
// May 7, 08:04:00
DateTime userDateTime = new DateTime(2009, 5, 7, 8, 4, 0);
DateTime utcDateTime = userDateTime.Subtract(tzi.BaseUtcOffset);

这篇关于如何在 ASP.NET 中使用时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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