Advertisement
Virajsinh

Time Format Converter in JavaScript

Sep 16th, 2021 (edited)
1,071
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const convertFrom24To12Format = (time24) => {
  2.   const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
  3.   const period = +sHours < 12 ? 'AM' : 'PM';
  4.   const hours = +sHours % 12 || 12;
  5.  
  6.   return `${hours}:${minutes} ${period}`;
  7. }
  8. const convertFrom12To24Format = (time12) => {
  9.   const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
  10.   const PM = period === 'PM';
  11.   const hours = (+sHours % 12) + (PM ? 12 : 0);
  12.  
  13.   return `${('0' + hours).slice(-2)}:${minutes}`;
  14. }
  15.  
  16. function formatAMPM(date) {
  17.   var hours = date.getHours();
  18.   var minutes = date.getMinutes();
  19.   var ampm = hours >= 12 ? 'pm' : 'am';
  20.   hours = hours % 12;
  21.   hours = hours ? hours : 12; // the hour '0' should be '12'
  22.   minutes = minutes < 10 ? '0'+minutes : minutes;
  23.   var strTime = hours + ':' + minutes + ' ' + ampm;
  24.   return strTime;
  25. }
  26.  
  27. console.log(formatAMPM(new Date));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement