简体   繁体   English

如何格式化js日期?

[英]How to format a js date?

I am writing this code but it seems I don't get the result I want. 我正在编写此代码,但似乎没有得到想要的结果。 This is a Real Time Clock. 这是一个实时时钟。

<p id="time"></p>

<script type="text/javascript">
function updateTime(){
  $('#time').html(new Date());
}

$(function(){
  setInterval(updateTime, 1000);
});
</script>

This is the Result: 结果如下:

Tue Aug 15 2017 13:34:09 GMT+0800 (China Standard Time)

How Can I format the Date and Time to this: "Tue August 15, 2017 1:30pm" 如何将日期和时间的格式设置为: "Tue August 15, 2017 1:30pm"

Using moment.js this is easy to achieve 使用moment.js,这很容易实现

var dt = moment([2015, 1, 14, 15, 25, 50, 125]);
dt.format("dddd, MMMM Do YYYY, h:mm:ss a"); //Prints "Sunday, February 14th 2015, 3:25:50 pm"

I suggest toDateString() and toLocaleTimeString() 我建议toDateString()toLocaleTimeString()

var now = new Date(); // Tue Aug 15 2017 14:05:13 GMT+0800 (中国标准时间)
var date = now.toDateString(); // "Tue Aug 15 2017"
var time = now.toLocaleTimeString(); // "下午2:05:13"
var flag = time.indexOf('下午') === 0 ? 'pm' : 'am';
time = time.slice(2) + flag; // "2:08:52pm"
console.log(date + ' ' + time); // "Tue Aug 15 2017 2:08:52pm"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM