I've made an object that displays the date and time live.
I would like to know how I can separate the time part from the date so I can have it in its own HTML element so I can apply different styling to it?
I'm not that advanced with JavaScript, and I find working with the date object very complicated.
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;
}
};
Usage
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
HTML
<span id="date"></span> - <span id="time"></span>
js parsing date and time. We can parse a string representation of date and time by passing the date and time format to the moment function. const moment = require('moment'); let day = "03/04/2008"; let parsed = moment(day, "DD/MM/YYYY"); console.
One of the best ways to Separate a date from a date and time value is by using the INT function. INT function takes an integer from a number and left out the fractional part. In the above example, you have the INT function that takes the reference from cell A1 where you have date and time in a numeric value.
Use date.toLocaleDateString()
for the date part, and date.toLocaleTimeString()
for the time part.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With