【问题标题】:Get time from datetime in jquery从jquery中的日期时间获取时间
【发布时间】:2013-03-06 11:17:16
【问题描述】:

jquery如何从日期时间中获取时间

假设,

datetime = Wed Mar 06 2013 11:30:00 GMT+0530 (IST)

我只需要 11:30:00 这样就可以了

time = 11:30:00

【问题讨论】:

  • 您要么拆分字符串(这很难看),要么只请求时间作为输出。你现在是怎么做到的?
  • 你想从当前日期获取当前时间

标签: jquery datetime


【解决方案1】:

您可以使用 JavaScript 轻松完成。

使用 Date.prototype.toLocaleTimeString

var date = new Date();
console.log(date.toLocaleTimeString('pt-BR'));
// Output: "20:30:39"

一些语言环境会给你不同的结果,这就是为什么我使用pt-BR 格式(24 小时没有 AM/PM)(时区将保持不变,这只会改变格式)。 您还可以使用任何其他语言环境并将 {hour12:false} 作为选项传递。

const event = new Date('August 19, 1975 23:15:30 GMT+00:00');
var options = {hour12:false}
console.log("en-US (options): " + event.toLocaleTimeString('en-US', options));
console.log("en-US          : " + event.toLocaleTimeString('en-US'));
console.log("ar-EG (options): " + event.toLocaleTimeString('ar-EG', options));
console.log("ar-EG          : " + event.toLocaleTimeString('ar-EG'));
console.log("pt-BR (options): " + event.toLocaleTimeString('pt-BR', options));
console.log("pt-BR          : " + event.toLocaleTimeString('pt-BR'));
/* Output: 
"en-US (options): 20:15:30"
"en-US          : 8:15:30 PM"
"ar-EG (options): ٢٠:١٥:٣٠"
"ar-EG          : ٨:١٥:٣٠ م"
"pt-BR (options): 20:15:30"
"pt-BR          : 20:15:30"
*/

【讨论】:

    【解决方案2】:

    试试这个来获取当天的当前时间

    $(document).ready(function() {
        var today = new Date();
        var cHour = today.getHours();
        var cMin = today.getMinutes();
        var cSec = today.getSeconds();
        alert(cHour+ ":" + cMin+ ":" +cSec );
    });
    

    【讨论】:

    【解决方案3】:

    查看W3C Javascript Datetime Object Reference

    var hours = datetime.getHours(); //returns 0-23
    var minutes = datetime.getMinutes(); //returns 0-59
    var seconds = datetime.getSeconds(); //returns 0-59
    

    你的问题:

    if(minutes<10)
      minutesString = 0+minutes+""; //+""casts minutes to a string.
    else
      minutesString = minutes;
    

    【讨论】:

    • 谢谢,但我怎样才能让它显示为 hh : mm : ss 格式。现在当它 12 时它显示 12:0:0,我想要 12:00:00。
    【解决方案4】:

    这是一个解决方案,

    创建一个 Javascript 日期:

    var aDate = new Date(
        Date.parse('Wed Mar 06 2013 11:30:00 GMT+0530 (IST)');
    );
    

    构建输出字符串:

    var dateString = '';
    
    var h = aDate.getHours();
    var m = aDate.getMinutes();
    var s = aDate.getSeconds();
    
    if (h < 10) h = '0' + h;
    if (m < 10) m = '0' + m;
    if (s < 10) s = '0' + s;
    
    dateString = h + ':' + m + ':' + s;
    

    文档链接: http://www.w3schools.com/jsref/jsref_obj_date.asp

    【讨论】:

    • var datetime 不是字符串。 Date.parse 需要一个字符串。
    • Stuart Eske:谢谢,但我怎样才能让它显示为 hh : mm : ss 格式。现在当它 12 时它显示 12:0:0,我想要 12:00:00。
    • 没有简单的方法可以做到这一点,看看这个链接。 Link@开发者
    【解决方案5】:

    用优秀的momentjs怎么样

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      相关资源
      最近更新 更多