Home > Back-end >  How to add Current Date and Time into Table?
How to add Current Date and Time into Table?

Time:07-19

how can I add the current date and time with this format: 2022-07-17 17:50:20?

I already managed it with an input value but I need the current time.

function button1( table ){
        
var tableRef = document.getElementById(table);
var newRow   = tableRef.insertRow(-1);
        
var newCell  = newRow.insertCell(0);
var newElem = document.createElement( 'input' );
newElem.setAttribute("name", "timestamp");
newElem.setAttribute("type", "text");
newElem.setAttribute("value", " 2022-07-17 17:30:24 ");
newCell.appendChild(newElem);
        
newCell = newRow.insertCell(1);
newElem = document.createElement( 'input' );
newElem.setAttribute("name", "button_name" );
newElem.setAttribute("type", "text");
newElem.setAttribute("value", "Button_Name");
newCell.appendChild(newElem);

newCell = newRow.insertCell(2);
newElem = document.createElement( 'input' );
newElem.setAttribute("type", "button");
newElem.setAttribute("value", "Delete Row");
newElem.setAttribute("onclick", 'deleteRow(this)')
newCell.appendChild(newElem);

CodePudding user response:

You can format ISO Date by JavaScript functions as follows:

// Create element:
var todayDate = new Date().toISOString();
const dateField = document.createElement("p");
dateField.innerText = new Date().toISOString().split('.')[0].split('T').join(' ');

// Append to body:
document.body.appendChild(dateField);

// Output: 2022-07-17 16:31:22

CodePudding user response:

You should use built-in Date object in Javascript, like this:

let currentdate = new Date(); 
let datetime = currentdate.getFullYear()   "-"
                  String((currentdate.getMonth()   1)).padStart(2,"0")    "-" 
                  String(currentdate.getDate()).padStart(2,"0")   " "
                  String(currentdate.getHours()).padStart(2,"0")   ":"  
                  String(currentdate.getMinutes()).padStart(2,"0")   ":" 
                  String(currentdate.getSeconds()).padStart(2,"0");
//The ` 1` on the getMonth() is used because in Javascript January is 0.
console.log(datetime);

By the way, I suggest you make all your vars into lets as that's the current standard. There's a very fine difference between them (let is block scoped while var is functional scoped).

  • Related