javascript convert datetime to date and time

631 0 0 0

Last Updated : 2024-04-20 04:15:29

this snippet will teach you how to convert datetime to time and date individually

To convert datetime to date


let currentDate = new Date(value['datetime']);   // CHANGE value['datetime] TO YOUR DATETIME VALUE
let date = currentDate.getDate();
let month = currentDate.getMonth();
let year = currentDate.getFullYear();
let dateString = date + "-" +(month + 1) + "-" + year;

To convert datetime to time


let currentDate = new Date(value['datetime']);  // CHANGE value['datetime] TO YOUR DATETIME VALUE
let hours = currentDate.getHours();
let minutes = currentDate.getMinutes();
let ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
let strTime = hours + ':' + minutes + ' ' + ampm;

 

Mahmoud Anwar

Mahmoud Anwar

Back End Developer with a passion for developing innovative web applications that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. Also has the proven ability to motivate, educate, and collaborate effectively to build web applications and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs, highlight their core competencies, and further their success.