Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การแปลงวินาทีเป็นชั่วโมงและนาทีใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับจำนวนวินาที และคืนค่าจำนวนชั่วโมงและนาทีที่อยู่ในวินาทีเหล่านั้น

อินพุต

const seconds = 3601;

เอาต์พุต

const output = "1 hour(s) and 0 minute(s)";

ตัวอย่าง

โค้ดตัวอย่างดังนี้:

const seconds = 3601;
const toTime = (seconds = 60) => {
  const hR = 3600;
  const mR = 60;
  let h = parseInt(seconds / hR);
  let m = parseInt((seconds - (h * 3600)) / mR);
  let res = '';
  res += (`${h} hour(s) and ${m} minute(s)`)
  return res;
};
console.log(toTime(seconds));

ผลลัพธ์

"1 hour(s) and 0 minute(s)"