Pau*_*haw 18 .net c# datetime nodatime
我希望将Noda时间用于一个相当简单的应用程序,但是我很难找到任何文档来处理一个非常基本的用例:
我有一个登录用户,并将在设置中存储他们的首选时区.来自客户端的任何日期/时间以已知的文本格式(例如"dd/MM/yyyy HH:mm"),具有已知的时区id(例如"Europe/London").我计划将这些时间转换为UTC/Noda Instants,以防止需要在数据库中存储每个日期的时区信息.
首先,这听起来像是一种明智的做法吗?我可以自由地改变任何东西,所以很乐意设置一个更好/更明智的课程.数据库是MongoDb,使用C#驱动程序.
我试过的是沿着这些方向,但努力克服第一步!
var userSubmittedDateTimeString = "2013/05/09 10:45";
var userFormat = "yyyy/MM/dd HH:mm";
var userTimeZone = "Europe/London";
//noda code here to convert to UTC
//Then back again:
Run Code Online (Sandbox Code Playgroud)
我知道有人会问"你有什么尝试",我所拥有的是各种失败的转换.很高兴被指向"Noda时间入门"页面!
Jon*_*eet 21
我计划将这些时间转换为UTC/Noda Instants,以防止需要将所有时区信息与数据库中的每个日期一起存储.
如果您以后不需要知道原始时区,那就没问题了.(例如,如果用户更改时区,但仍希望在原始时区中重复出现某些内容).
无论如何,我会将其分为三个步骤:
LocalDateTime
ZonedDateTime
Instant
就像是:
// TODO: Are you sure it *will* be in the invariant culture? No funky date
// separators?
// Note that if all users have the same pattern, you can make this a private
// static readonly field somewhere
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy/MM/dd HH:mm");
var parseResult = pattern.Parse(userSubmittedDateTimeString);
if (!parseResult.Success)
{
// throw an exception or whatever you want to do
}
var localDateTime = parseResult.Value;
var timeZone = DateTimeZoneProviders.Tzdb[userTimeZone];
// TODO: Consider how you want to handle ambiguous or "skipped" local date/time
// values. For example, you might want InZoneStrictly, or provide your own custom
// handler to InZone.
var zonedDateTime = localDateTime.InZoneLeniently(timeZone);
var instant = zonedDateTime.ToInstant();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10168 次 |
最近记录: |