简体   繁体   中英

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"

Using moment.js this is easy to achieve

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()

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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