加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 02:00:38 所属栏目:百科 来源:网络整理
导读:我目前正在使用NodaTime,这是基于我在C#的DateTime类中处理时区的挫败感.到目前为止,我真的很高兴. public static string nodaTimeTest(string input){ var defaultValue = new OffsetDateTime(new LocalDateTime(2000,1,0),Offset.Zero); var pattern = Off
我目前正在使用NodaTime,这是基于我在C#的DateTime类中处理时区的挫败感.到目前为止,我真的很高兴.

public static string nodaTimeTest(string input)
{
    var defaultValue = new OffsetDateTime(new LocalDateTime(2000,1,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();
}

我有三个具体问题.上面是我使用的方法,我解析dateTime字符串.我有一个格式字符串,它允许我如何解析输入.我的问题是:

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

如何将时间转换为Unix时间戳?它似乎没有内置的方法.

使用此方法:

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

        return result.Value.ToString();
    }

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

这是理想的行为吗?

解决方法

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是一个OffsetDateTime. Instant类型使用Unix纪元,因此您可以这样做:

int unixTime = result.Value.ToInstant().Ticks / NodaConstants.TicksPerSecond;

>请注意,Unix时间戳精确到最接近的秒.如果您要传递给JavaScript,则需要使用TicksPerMillisecond并将其返回很长时间.

… 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读