Getting Started with Noda Time

ε祈祈猫儿з 提交于 2019-12-20 08:48:33

问题


I am looking to use Noda time for a fairly simple application, however I am struggling to find any documentation to handle a very basic use case:

I have a logged in user, and will be storing their preferred timezone in the settings. Any date/times that come from the client come in a known text format (e.g. "dd/MM/yyyy HH:mm"), with a known time zone id (e.g. "Europe/London"). I was planning on converting these times to UTC/Noda Instants to prevent the need to store the time zone info with each date in the database.

Firstly, does this sound like a sensible approach? I am free to change pretty much anything, so would be happy to be set on a better/more sensible course. The database is MongoDb, using the C# driver.

What I have tried is along these lines, but struggling to get over the first step!

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 know someone will ask "what have you tried", to which all i have is various failed conversions. Happy to be pointed to an "Getting started with Noda time" page!


回答1:


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.

That's fine if you don't need to know the original time zone later on. (e.g. if the user changes time zone, but still wants something recurring in the original time zone).

Anyway, I would separate this out into three steps:

  • Parsing into a LocalDateTime
  • Converting that into a ZonedDateTime
  • Converting that into an Instant

Something like:

// 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();


来源:https://stackoverflow.com/questions/15568561/getting-started-with-noda-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!