【问题标题】:Is there an easy way to convert seconds into an ISO 8601 format for use in the schema.org video metadata?有没有一种简单的方法可以将秒转换为 ISO 8601 格式以用于 schema.org 视频元数据?
【发布时间】:2014-11-20 21:11:28
【问题描述】:

我正在尝试在视频搜索结果中使用 Google 建议的 html 标记。他们建议将 schema.org 标记用于 SEO。

以下行是持续时间: <meta itemprop="duration" content="T1M33S" />

根据 Google 和 Schema.org -“ISO 8601 格式的视频的持续时间”,时间必须采用 ISO 8601 格式。

我有一些 jquery 从 html5 视频元素中提取视频的持续时间。提取的持续时间以秒为单位。

将秒转换为 ISO 8601 格式的最佳方法是什么?

C#、Javascript 或 JQuery 中有什么东西可以轻松完成这项任务吗?

谢谢

【问题讨论】:

  • 不知何故,我觉得如果你要“用 jQuery 拉视频的持续时间”,没有搜索引擎会选择它。
  • 我从视频元素中提取持续时间数据并将其加载到以下标签中。
  • 确实如此。我的大脑是糊状的。我正在尝试找出从 mp4 获取视频持续时间并将其显示在该元标记上的最佳方法。我只需要谷歌就能看到它。
  • 如果我提取持续时间并在页面加载时使用 javascript 写出元标记,谷歌蜘蛛应该会看到标记对吗?
  • PT1M33S 等效于 PT93S 并且两者都是有效的 ISO 8601 持续时间。您只需:"PT" + seconds + "S".

标签: javascript c# jquery html


【解决方案1】:

获取此结果不需要 Jquery。然而,JavaScript 可以用于此。

首先可以在日期类中使用toISOString()函数:

var date = new Date();
date.toISOString();

但是,并非所有浏览器都支持它,因为它是 ECMAScript5 的一部分(大多数浏览器都支持,但请谨慎行事)。因此,您可以编写一个备份来执行此操作,如下所示:

if ( !Date.prototype.toISOString ) {
  ( function() {

    function pad(number) { // Add leading zero if necessary
      var r = String(number);
      if ( r.length === 1 ) {
        r = '0' + r;
      }
      return r;
    }

    Date.prototype.toISOString = function() { // Return the date as a ISO string
      return this.getUTCFullYear()
        + '-' + pad( this.getUTCMonth() + 1 )
        + '-' + pad( this.getUTCDate() )
        + 'T' + pad( this.getUTCHours() )
        + ':' + pad( this.getUTCMinutes() )
        + ':' + pad( this.getUTCSeconds() )
        + '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
        + 'Z';
    };

  }() );
}

现在您需要做的就是运行 javascript。

【讨论】:

    【解决方案2】:

    在 C# 中,您可以使用 TimeSpan 和自定义格式字符串:

    var duration = TimeSpan.FromSeconds(secs);
    
    string iso8601 = duration.ToString("'P'd'DT'h'H'm'M's'S'");
    

    (n.b. 我实际上并没有运行它)

    【讨论】:

      猜你喜欢
      • 2016-08-26
      • 2020-05-02
      • 2010-11-14
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 2010-09-06
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多