创建一个表示"today"的NodaTime LocalDate. [英] Create a NodaTime LocalDate representing "today"

查看:48
本文介绍了创建一个表示"today"的NodaTime LocalDate.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建代表今天"的LocalDate实例的推荐方法是什么?我期望LocalDate类中有一个静态的"Now"或"Today"属性,但没有.我当前的方法是使用DateTime.Now:

What is the recommended way to create a LocalDate instance that represents "today". I was expecting there to be a static "Now" or "Today" property in the LocalDate class, but there isn't. My current approach is to use DateTime.Now:

var now = DateTime.Now;
LocalDate today = new LocalDate(now.Year, now.Month, now.Day);

有更好的方法吗?

推荐答案

首先要认识到,当您说今天"时,对于世界不同地区的不同人来说答案可能会有所不同.因此,为了获取当前的本地日期,您必须牢记一个时区.

First recognize that when you say "today", the answer could be different for different people in different parts of the world. Therefore, in order to get the current local date, you must have a time zone in mind.

Noda Time通过从 IClock 实现(例如系统时钟)调用 Now 时给您一个 Instant 来正确地对此建模.即时是通用的,因此您只需将其转换为某个时区即可获取该时区的本地日期.

Noda Time correctly models this by giving you an Instant when you call Now from an IClock implementation such as the system clock. An instant is universal, so you just need to convert it to some time zone to get that time zone's local date.

// get the current time from the system clock
Instant now = SystemClock.Instance.Now;

// get a time zone
DateTimeZone tz = DateTimeZoneProviders.Tzdb["Asia/Tokyo"];

// use now and tz to get "today"
LocalDate today = now.InZone(tz).Date;

那是最少的代码.当然,如果您想使用计算机的本地时区(就像您对 DateTime.Now 所做的那样),则可以这样获得:

That's the minimal code. Of course, if you want to use the computer's local time zone (like you did with DateTime.Now), you can get it like so:

DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault();

要真正正确地实现它,您应该从 IClock 接口调用 .Now ,这样就可以用伪时钟代替系统时钟来进行单元测试.

And to really implement it properly, you should call .Now from the IClock interface, such that you could substitute the system clock with a fake clock for your unit tests.

这是一个很好的例子,说明了Noda Time如何故意不向您隐藏事物.当您调用 DateTime.Now 时,所有这些仍然在后台进行,但是您根本看不到.您可以在用户指南中了解有关Noda Time设计理念的更多信息.

This is a great example of how Noda Time intentionally doesn't hide things from you. All this is still going on under the hood when you call DateTime.Now, but you just don't see it. You can read more about Noda Time's design philosophy in the user guide.

这篇关于创建一个表示"today"的NodaTime LocalDate.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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