【问题标题】:How do I get current time in the format "2011-11-03 11:18:04" in javascript?如何在javascript中以“2011-11-03 11:18:04”格式获取当前时间?
【发布时间】:2014-03-24 11:41:32
【问题描述】:

我想让 javascript 以类似于 "2011-11-03 11:18:04" 的格式返回当前时间。

我试过var XX = date(),但返回的格式不是我想要的。好像

2013 年 3 月 15 日星期二 06:45:40 GMT-0500

如何将时间格式化为"2011-11-03 11:18:04"

非常感谢。

【问题讨论】:

  • date.getYear() + '-' + (date.getMonth() + 1) + '-' + date.getDay()
  • 为什么是 -ve 2 分?为什么这对新手来说不是一个有效的问题?
  • 因为这类问题已经回答过很多次了。例如here
  • 我明白了。谢谢和抱歉。

标签: javascript date datetime datetime-format


【解决方案1】:

正确创建日期后(var xx = new Date();,注意大写和new),您有两个选择:

  1. 使用Date实例(MDN|specification)的各种方法,自己构建字符串。

  2. 使用像 MomentJS 这样的库来为您完成这项工作。

【讨论】:

  • MomentJS 看起来是一个很好的时间格式化库。谢谢!
【解决方案2】:

使用Date 函数-

//MM-dd-yyyy HH:mm:ss format
function formatDateTime(d){
  function addZeros(n){
     return n < 10 ? '0' + n : '' + n;
  }
  return addZeros(d.getFullYear()+1)+"-"+ addZeros(d.getMonth()) + "-" + d.getDate() + " " + 
           addZeros(d.getHours()) + ":" + addZeros(d.getMinutes()) + ":" + addZeros(d.getMinutes());
}

momentjs-

var now = moment().format("YYYY-MM-DD HH:mm:ss");

jsFiddle

【讨论】:

  • 我喜欢这个答案,因为使用momentjs,对于像我这样的新手来说,代码看起来最易读:)
【解决方案3】:

这是一个完整的工作解决方案

<script type="text/javascript">
function giveNewDate(){
var d = new Date();
var r = d.getFullYear()+"-"+zPlus(d.getMonth())+"-"+zPlus(d.getDate())+" "+zPlus(d.getHours())+":"+zPlus(d.getMinutes())+":"+zPlus(d.getSeconds());

function zPlus(digit){
    var digit = parseInt(digit);
    if (digit < 10){
    return "0"+digit;
    }else{
        return ""+digit;
    }
}
return r;
}

//to use: just call the giveNewDate() function
alert(giveNewDate());
</script>

在您的脚本中,只需在需要文本出现的地方调用 giveNewDate() 函数。

祝你有美好的一天!

:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-09
    • 2015-05-29
    • 2015-07-04
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2021-02-05
    相关资源
    最近更新 更多