0

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"

Sam Axe
  • 31,472
  • 7
  • 52
  • 80
Jboy
  • 147
  • 1
  • 9
  • 1
    I'm kinda sure this has been answered multiple times on SO, what have you tried yourself so far? – Carsten Løvbo Andersen Aug 15 '17 at 05:38
  • Formatting dates in Javascript is pretty limited. For any type of custom date formatting you could check out [moment.js](https://momentjs.com) – jackarms Aug 15 '17 at 05:40
  • 3
    Possible duplicate of [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – t.niese Aug 15 '17 at 05:44

2 Answers2

0

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"
Navoneel Talukdar
  • 3,581
  • 3
  • 17
  • 39
0

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"
JiangangXiong
  • 1,930
  • 1
  • 8
  • 14