Kid*_*ond 6 html javascript date
我制作了一个显示日期和时间的对象.
我想知道如何将时间部分与日期分开,以便我可以将它放在自己的HTML元素中,这样我就可以应用不同的样式了吗?
我不是那么先进的JavaScript,我觉得使用日期对象非常复杂.
LiveDateTime.js
'use strict';
function LiveDateTime(dateEl, options) {
this.dateEl = dateEl;
this.options = options;
this.timestamp;
this.offset;
this.start();
}
LiveDateTime.prototype = {
start: function () {
var now = !this.timestamp ? new Date() : new Date(this.timestamp),
self = this;
(function update() {
self.dateEl.innerHTML = now.toLocaleString(self.options.locale, self.options);
now.setSeconds(now.getSeconds() + 1);
self.timeoutId = setTimeout(update, 1000);
})();
},
stop: function () {
clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
};
Run Code Online (Sandbox Code Playgroud)
用法
var liveDateTime = new LiveDateTime(document.getElementById('date'), {
locale: 'FR',
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
//output example: vendredi 13 mars 2015 23:14:12
Run Code Online (Sandbox Code Playgroud)
HTML
<span id="date"></span> - <span id="time"></span>
Run Code Online (Sandbox Code Playgroud)
使用date.toLocaleDateString()作为日期部分.
和date.toLocaleTimeString()为时间部分.
您可以使用 Date 可用方法格式化您的日期:
var now = new Date()
var date = now.toLocaleDateString();
var time = now.toLocaleTimeString();
console.log(date + ' ' + time)
Run Code Online (Sandbox Code Playgroud)