.net - 如何在 NodaTime 中获取 "start of the year/month"?

标签 .net datetime nodatime

我知道有 DateTimeZone.AtStartOfDay 方法,但是是否有类似的方法来获取年/月的开始?我知道最简单的方法是将它们硬编码为“X 的第一天和 30 秒”(我做了 LocalDateTime start = LocalDateTime.FromDateTime(new DateTime(2014, 1, 1, 0, 0, 1, DateTimeKind. Utc));),但我认为这远非最佳实践

最佳答案

您当然不需要通过 DateTime - 但要在特定时区获得一年的开始,我只需使用:

var startOfYear = zone.AtStartOfDay(new LocalDate(year, 1, 1));

请注意,这对于获取 ZonedDateTime 和年初之间的持续时间 很有用。对于期间(例如 5 个月、2 天、3 小时),您只需要使用 LocalDateTime,它不会考虑时区。 (周期算术在时区面前变得很奇怪......)

要获得 LocalDateTime,您可以使用:

var startOfYear = new LocalDate(year, 1, 1).AtMidnight();

...虽然不能保证该日期/时间出现在任何特定时区(或只出现一次)。

关于.net - 如何在 NodaTime 中获取 "start of the year/month"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31935943/

相关文章:

c# - 有没有办法导航到接口(interface)背后方法的实际实现?

c# - 如何使用 SqlParameterCollection?

c# - 右对齐字符串格式的货币

c# - String.Replace 在运行时不替换字符串

Python 日期时间 : use strftime() with a timezone-aware date

sql-server - 将日期时间转换为 nvarchar 但保留格式

c# - DateTime 到 LocalDate (NodaTime)

c++ - 获得绝对时间的更好方法?

javascript - 如何将刻度转换为 momentjs 对象

c# - 使用 NodaTime 的明确 DateTime 表示——这可以用更少的仪式来完成吗?