gpt4 book ai didi

c# - NodaTime转Unix时间戳及LocalDateTime的重要性

转载 作者:行者123 更新时间:2023-11-30 14:10:49 27 4
gpt4 key购买 nike

基于我在 C# 的 DateTime 类中处理时区的挫败感,我目前正在使用 NodaTime。到目前为止,我真的很高兴。

public static string nodaTimeTest(string input)
{
var defaultValue = new OffsetDateTime(new LocalDateTime(2000, 1, 1, 0, 0), Offset.Zero);
var pattern = OffsetDateTimePattern.Create("yyyy-MM-dd'T'HH:mm:sso<m>", CultureInfo.InvariantCulture, defaultValue);
var result = pattern.Parse(input).Value;

return result.ToString();
}

我有三个具体问题。以上是我在解析日期时间字符串时使用的方法。我有一个 format 字符串,它允许我如何解析输入。我的问题是:


我的 LocalDateTime(..) 是什么重要吗?我使用的方法是 Matt Johnson 的 Stack example ,他的日期是 2000, 1, 1, 0, 0。我认为这很奇怪,因为我知道的大多数日期类都使用大纪元时间 1970, 1, 1, 0 ,0,所以我更改了我的方法以包含大纪元日期,但输出是相同的:

enter image description here


如何将时间转换为 Unix 时间戳?似乎没有这样做的内置方法。


使用这个方法:

    public static string nodaTimeTest6(string input, int timeZone)
{
// var defaultValue = new OffsetDateTime(new LocalDateTime(2000, 1, 1, 0, 0), Offset.Zero);
var defaultValue = new OffsetDateTime(new LocalDateTime(2000, 1, 1, 0, 0), Offset.FromHours(timeZone));
var pattern = OffsetDateTimePattern.Create("yyyy-MM-dd'T'HH:mm:sso<m>", CultureInfo.InvariantCulture, defaultValue);
var result = pattern.Parse(input);

return result.Value.ToString();
}

我正在用这种方法测试 NodaTime 的能力——具体来说,我想知道我是否可以在内部定义了偏移量的日期/时间中解析,同时,我的 timeZone input 还允许输入时区/偏移量。有趣的是,我的输入 timeZone 被忽略了,所以我的 nodaTimeTest6 输出中的偏移量是输入日期字符串:

enter image description here

这是期望的行为吗?

最佳答案

Does it matter what my LocalDateTime(..) is?

  • OffsetDateTimePattern.Create 方法需要一个默认值。它仅在解析失败且您在使用 result.Value 之前未检查 result.Success 时使用。

  • 其他模式有一个不需要默认值的重载(参见 issue #267 )。我选择了 2000-01-01T00:00:00.0000000+00:00 的特定默认值,因为它类似于 the other patterns use。当您没有明确指定默认值时。

  • 不过确实没有任何意义。您可以使用任何您希望的默认设置。

How do I convert the time to a Unix timestamp? It does not appear there's a built-in method to do so.

  • result.Value 是一个 OffsetDateTimeInstant 类型使用 Unix 纪元,因此您可以这样做:

    int unixTime = result.Value.ToInstant().Ticks / NodaConstants.TicksPerSecond;
  • 请注意,Unix 时间戳精确到最接近的秒。如果要传递给 JavaScript,则需要使用 TicksPerMillisecond 并以 long 形式返回它。

... I was wondering if I can parse in a date/time that HAS offset defined inside, and at the same time, my timeZone input also allows input of timezones/offsets.

  • 抱歉,我不完全明白你在这里问什么。你能澄清一下吗?

  • 从您提供的代码来看,您似乎混淆了默认值的偏移量和输入字符串的偏移量。默认值仅在解析失败时使用。

  • 如果您想控制偏移量而不是将其包含在输入中,则使用 LocalDateTimePattern 而不是 OffsetDateTimePattern 来进行解析。解析后,您可以将其与特定区域相关联。

  • 此外,请注意您的命名约定。 int timeZone 没有意义(这是一个偏移量,而不是时区)。可能是 int offsetHours,或者更好的是 Offset timeZoneOffset

关于c# - NodaTime转Unix时间戳及LocalDateTime的重要性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22389644/

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