将NodaTime转换为Unix时间戳以及LocalDateTime的重要性

问题描述 投票:0回答:1

我目前正在使用 NodaTime,因为我在 C# 的

DateTime
类中处理时区时遇到了挫折。到目前为止,我真的很高兴。

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
输入还允许输入时区/偏移量。有趣的是,我的输入
timeZone
被忽略,因此我的输出
nodaTimeTest6
中的偏移量是输入日期字符串:

enter image description here

这是期望的行为吗?

c# nodatime
1个回答
7
投票

我的 LocalDateTime(..) 是什么重要吗?

  • OffsetDateTimePattern.Create
    方法需要默认值。仅当解析失败并且您在使用
    result.Success
    之前没有检查
    result.Value
    时才使用它。

  • 其他模式具有不需要默认值的重载(请参阅issue #267)。我选择了

    2000-01-01T00:00:00.0000000+00:00
    的特定默认值,因为它类似于当您未明确指定默认值时 其他模式使用的

  • 虽然确实没有任何意义。您可以使用任何您想要的默认值。

如何将时间转换为 Unix 时间戳?似乎没有内置方法可以做到这一点。

  • result.Value
    是一个
    OffsetDateTime
    Instant
    类型使用Unix纪元,所以你可以这样做:

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

    TicksPerMillisecond
    并在
    long
    中返回它。

...我想知道是否可以解析内部定义了偏移量的日期/时间,同时,我的

timeZone
输入还允许输入时区/偏移量。

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

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

  • 如果您想控制偏移量而不是将其包含在输入中,请使用
  • LocalDateTimePattern

    而不是

    OffsetDateTimePattern
    进行解析。解析后,您可以将其与特定区域关联。
    
    

  • 另外,请注意命名约定。
  • int timeZone

    没有意义(这是偏移量,而不是时区)。也许

    int offsetHours
    ,或者更好,
    Offset timeZoneOffset
    
    

© www.soinside.com 2019 - 2024. All rights reserved.