Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split the date and time into two elements?

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>
like image 731
Kid Diamond Avatar asked Mar 13 '15 22:03

Kid Diamond


People also ask

How do you separate moments from date and time?

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.

How do I separate a date and time in a spreadsheet?

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.


1 Answers

Use date.toLocaleDateString() for the date part, and date.toLocaleTimeString() for the time part.

like image 134
QuentinUK Avatar answered Oct 17 '22 06:10

QuentinUK