Skip to content Skip to sidebar Skip to footer

Javascript Date And Time Formatting,

I have read a lot of thread about the subject, but i'm not much into programming... i've made some tests but never acheive what i wanted. Here we have a html template we have to mo

Solution 1:

As opposed to using an external JavaScript library for a simple task. You should be able to achieve the same with Vanilla js.

Refer to this: Where can I find documentation on formatting a date in JavaScript?

In short:

var d = newDate();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero basedvar curr_year = d.getFullYear();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
console.log(curr_date + "-" + curr_month + "-" + curr_year + " " + curr_hour + ":" + curr_min);

The above snippet should have all the code you need.

For your specific implementation, you will need to do the below:

<script>var d = newDate();
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1; //Months are zero basedvar curr_year = d.getFullYear();
    var curr_hour = d.getHours();
    var curr_min = d.getMinutes();
    var formattedDate = curr_date + "-" + curr_month + "-" + curr_year + " " + curr_hour + ":" + curr_min;
    document.getElementById("DATE").innerHTML = formattedDate;
</script>

Solution 2:

A function for the format you require is fairly simple. The following will return a string for a provided Date, or the current date if none passed.

functionformatDate(date) {
  var d = date || newDate();
  functionz(n){return (n<10?'0':'')+n}
  returnz(d.getDate()) + '-' + 
         z(d.getMonth()+1) + '-' +
         d.getFullYear() + ' ' +
         z(d.getHours()) + ':' +
         z(d.getMinutes());
}
document.write(formatDate());

BTW, you can't use the same token for two separate parts. While there is no standard or even consistency for formatting tokens, your format would be more commonly expressed as:

DD-MM-YYYY HH:mm

Which is compatible with moment.js and a few others, though there are many other token sets to represent the same format.

Solution 3:

To achieve your goal simply try following codes:

First of all, inside the head tag add the below line of code:

<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>

Finally, change your existing line of code:

document.getElementById("DATE").innerHTML = moment(d).format('DD-MM-YYYY HH:MM');

Happy coding :)

Post a Comment for "Javascript Date And Time Formatting,"