【问题标题】:Extract time from moment js object从时刻 js 对象中提取时间
【发布时间】:2015-03-14 18:06:25
【问题描述】:

如何使用 moment.js 提取时间?

"2015-01-16T12:00:00"

它应该返回“12:00:00 pm”。 返回的字符串将传递给下面的时间选择器控件。

http://jdewit.github.com/bootstrap-timepicker 

有什么想法吗?

【问题讨论】:

    标签: javascript datetime time momentjs angular-moment


    【解决方案1】:

    如果您阅读文档 (http://momentjs.com/docs/#/displaying/),您可以找到以下格式:

    moment("2015-01-16T12:00:00").format("hh:mm:ss a")
    

    见 JS Fiddle http://jsfiddle.net/Bjolja/6mn32xhu/

    【讨论】:

    • 例如 moment("2015-01-16T16:00:00").format("HH:mm:ss a") 返回为 "16:00:00 pm" ???应该是“下午 4:00:00”!
    • 是的,看看这里jsfiddle.net/Bjolja/6mn32xhu 你是什么意思它不起作用?错误信息?输出格式错误?
    • 我预计“下午 4:00:00”而不是下午 16 点
    • 将 HH 更改为 hh,因此 moment("2015-01-16T16:00:00").format("hh:mm:ss a")。我也更新了小提琴
    【解决方案2】:

    你可以这样做

    var now = moment();
    var time = now.hour() + ':' + now.minutes() + ':' + now.seconds();
    time = time + ((now.hour()) >= 12 ? ' PM' : ' AM');
    

    【讨论】:

    • 该方法不考虑时区
    【解决方案3】:

    这是使用格式的好方法:

    const now = moment()
    now.format("hh:mm:ss K") // 1:00:00 PM
    now.format("HH:mm:ss") // 13:00:00
    

    红色更多关于moment sring format

    【讨论】:

      【解决方案4】:

      使用带有特定模式的format 方法来提取时间。 工作示例

      var myDate = "2017-08-30T14:24:03";
      console.log(moment(myDate).format("HH:mm")); // 24 hour format
      console.log(moment(myDate).format("hh:mm a")); // use 'A' for uppercase AM/PM
      console.log(moment(myDate).format("hh:mm:ss A")); // with milliseconds
      <script src="https://momentjs.com/downloads/moment.js"></script>

      【讨论】:

        猜你喜欢
        • 2018-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-19
        • 1970-01-01
        • 2017-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多