【问题标题】:How can I convert a HH:mm:ss string to a JavaScript Date object?如何将 HH:mm:ss 字符串转换为 JavaScript Date 对象?
【发布时间】:2012-11-27 23:06:42
【问题描述】:

我有HH:mm:ss 格式的动态字符串(例如18:19:02)。如何将字符串转换为 JavaScript 日期对象(在 Internet Explorer 8、Chrome 和 Firefox 中)?

我尝试了以下方法:

   var d = Date.parse("18:19:02");
   document.write(d.getMinutes() + ":" + d.getSeconds());

【问题讨论】:

  • RTFM - 如果您只有时间,您无法创建日期。
  • 哪年哪月哪一天??
  • 如果日期不重要,但您想在 Date 对象上使用函数,请指定任意日期。
  • 您的问题解决了吗?
  • @Blazemonger 截至 2018 年,即使没有日期和时间,您也可以使用 new Date() 创建 Date 对象:请参阅 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: javascript jquery


【解决方案1】:

您不能直接从HH:mm:ss 这样的时间创建日期对象。

但是 - 假设您想要当前日期(Date 对象的日期部分是今天)或者对您的情况无关紧要 - 您可以执行以下操作:

let d = new Date(); // Creates a Date Object using the clients current time

let [hours, minutes, seconds] = "18:19:02".split(':');

d.setHours(+hours); // Set the hours, using implicit type coercion
d.setMinutes(minutes); // can pass Number or String - doesn't really matter
d.setSeconds(seconds);

// If needed, you could also adjust date and time zone

console.log(d.toString()); //Outputs desired time (+current day/timezone)

现在您有一个 Date 对象,其中包含您指定的时间以及您客户的当前日期和时区。

【讨论】:

    【解决方案2】:

    试试这个(没有 jQuery 和一个日期对象(它只是一个时间)):

    var
        pieces = "8:19:02".split(':')
        hour, minute, second;
    
    if(pieces.length === 3) {
        hour = parseInt(pieces[0], 10);
        minute = parseInt(pieces[1], 10);
        second = parseInt(pieces[2], 10);
    }
    

    【讨论】:

    【解决方案3】:

    由于缺少日期部分,Date 对象永远不会正确设置。这应该有效:

    var d = new Date("1970-01-01 18:19:02");
    document.write(d.getMinutes() + ":" + d.getSeconds());
    

    【讨论】:

      猜你喜欢
      • 2016-01-22
      • 1970-01-01
      • 2022-07-07
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多