gpt4 book ai didi

c# - 野田时间入门

转载 作者:IT王子 更新时间:2023-10-29 04:49:23 24 4
gpt4 key购买 nike

我希望将 Noda 时间用于一个相当简单的应用程序,但是我正在努力寻找任何文档来处理一个非常基本的用例:

我有一个登录用户,并将在设置中存储他们的首选时区。来自客户端的任何日期/时间都采用已知的文本格式(例如“dd/MM/yyyy HH:mm”)和已知的时区 ID(例如“欧洲/伦敦”)。我计划将这些时间转换为 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:

我知道有人会问“你试过什么”,对此我只有各种失败的转换。很高兴被指向“野田时间入门”页面!

最佳答案

I was planning on converting these times to UTC/Noda Instants to prevent the need to store all the time zone info with each date in the database.

没关系如果您以后不需要知道原来的时区。 (例如,如果用户更改时区,但仍希望在原始时区重复出现某些内容)。

无论如何,我会将其分为三个步骤:

  • 解析为 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();

关于c# - 野田时间入门,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15568561/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com