【问题标题】:how to convert ticks to momentjs object如何将刻度转换为 momentjs 对象
【发布时间】:2016-04-11 17:42:58
【问题描述】:

我正在使用 nodatime,它会返回刻度。如何使用 momentjs 将刻度转换为使用和格式?

public JsonResult Foo()
{
  var now = SystemClock.Instance.Now.Ticks;
  return Json(now, JsonRequestBehavior.AllowGet);
}

它返回long,例如14598788048897648

【问题讨论】:

    标签: javascript c# .net momentjs nodatime


    【解决方案1】:

    Moment.js 没有直接接受刻度的构造函数,但它确实有one that accepts the number of milliseconds that have elapsed since the epoch,这可能适合这个:

    // Dividing your ticks by 10000 will yield the number of milliseconds
    // as there are 10000 ticks in a millisecond
    var now = moment(ticks / 10000);
    

    This GitHub discussion in the NodaTime repository 讨论了使用扩展方法来支持此行为以及从您的服务器端代码返回毫秒数:

    public static long ToUnixTimeMilliseconds(this Instant instant)
    {
        return instant.Ticks / NodaConstants.TicksPerMillisecond;
    }
    

    【讨论】:

    • 其实你的答案很好,只是更喜欢使用标准格式而不是刻度。
    • 之前的cmets链好像被删除了。我在Hanselminutes talking about both NodaTime and Moment.js 上听了你的意见,所以我认为你对这两个库中的任何一个都比我了解的多得多,并且会知道什么时候会起作用。
    • 是的,我在回忆 0001 的 System.DateTime 纪元,但是 NodaTime 像 JS 和 moment 一样使用 1970。干杯!
    【解决方案2】:

    不要将Ticks 从您的 API 中泄漏出来。相反,使用NodaTime.Serialization.JsonNet 包允许像Instant 这样的NodaTime 类型以ISO8601 标准格式序列化。 moment.js 原生支持该格式。

    请参阅页面底部的the user guide page on serialization

    【讨论】:

    • 你认为你可以做一个关于如何使用它的代码演示吗?供将来参考。
    • 如果只是这一种方法,你也可以直接调用.ToDateTimeUtc(),让默认的序列化器来做。
    • 我明白了。但例如我使用上面相同的代码将其转换为其他DateTimeZoneProvider。我还可以使用ToDateTimeUtc() 的返回值转换为其他提供者吗?
    【解决方案3】:

    根据the documentation,Instant.Ticks 属性为:

    自 Unix 纪元以来的滴答数。

    还有,

    一个滴答等于 100 纳秒。一毫秒内有 10,000 个滴答声。

    Date 对象在其构造函数中采用自 Unix 纪元以来的毫秒数,并且由于 moment 在幕后使用 Date 构造函数,因此您可以使用:

    var value = moment(ticks/10000);
    

    【讨论】:

      猜你喜欢
      • 2011-12-19
      • 2011-11-15
      • 2010-09-28
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      相关资源
      最近更新 更多