Noob2018
Noob2018

Reputation: 1

How to convert date format in HTML using JS?

Really new to javascript, so really appreciate your help.

Part of my HTML code contains dates extracted from a form, which they will be printed.

<body> 
Test Date<br> 
<span id="test">{{TestDate|"dd/MM/yy"}}</span><br>
Test Date 2<br> 
<span id="test2">{{NextTest|"dd/MM/yy"}}</span><br>
</body>

TestDate and NextTest are data obtained from a form and result displayed. However, the date result is yyyy-MMM-dd.

I am trying to have it displayed as dd/MM/yy by using {{TestDate|"dd/MM/yy"}}. However, this doesn't seem to work.

I have seen several options to do this using js, but I am not sure how to use this with HTML, ( tag? and how to make it execute without a trigger / upon load so both dates will be in the correct format prior to printing.)

Eg var now = new Date(); now.format("dd/MM/yy"); // Returns, e.g., 08/01/18

But not sure how to incorporate/amend this into the above HTML for the date format change to take effect as I don't need a new date, but want to use the dates returned for TestDate and NextTest.

Or do I need to reference to span ID? if so, how would that work if both dates need converting?

Any help appreciated!

Echo

Upvotes: 0

Views: 7223

Answers (3)

Vivek
Vivek

Reputation: 2755

You can do something like below to implement the functionality. I have added a class customDate to all DOM elements that requires date format conversion and added the code for replacing them in the onload function.

window.onload = function() {
  var customDates = document.getElementsByClassName('customDate');
  for (var i=0; i<customDates.length; i++) {
    var customDate = new Date(customDates[i].innerHTML);
    var year = customDate.getFullYear();
 var month = (customDate.getMonth()+1).toString().padStart(2, '0');
    var day = customDate.getDate().toString().padStart(2, '0');
    document.getElementsByClassName('customDate')[i].innerHTML = day+"/"+month+"/"+year;
  }
}
<body> 
Test Date<br> 
<span class="customDate" id="test">2018-01-08</span><br>
Test Date 2<br> 
<span class="customDate" id="test2">2017-12-10</span><br>
</body>

Upvotes: 1

Issac Young
Issac Young

Reputation: 66

if u have many date format requirements, this lib would help moment.js

Upvotes: 0

Chandraveer
Chandraveer

Reputation: 159

Using Javascript you change using innerHTML element property. In your case you can do like this.

document.getElementById('test').innerHTML=now.format("dd/MM/yy"); 

Hope this will help you out.

Upvotes: 0

Related Questions