ভূমিকা
সময় ফরম্যাট `HH:MM:SS` (ঘন্টা:মিনিট:সেকেন্ড) কে টোটাল সেকেন্ডে রূপান্তর করা একটি সাধারণ টাস্ক। এই আর্টিকেলে একটি রোবাস্ট ফাংশন দেখানো হয়েছে যা ভিন্ন ভিন্ন ফরম্যাট হ্যান্ডল করতে পারে।
সম্পূর্ণ কোড
const timeString = '23:54:43';
const other = '12:30:00';
const withoutSeconds = '10:30';
const countSeconds = (str) => {
const [hh = '0', mm = '0', ss = '0'] = (str || '0:0:0').split(':');
const hour = parseInt(hh, 10) || 0;
const minute = parseInt(mm, 10) || 0;
const second = parseInt(ss, 10) || 0;
return (hour * 3600) + (minute * 60) + second;
};
console.log(countSeconds(timeString)); // 86083
console.log(countSeconds(other)); // 45000
console.log(countSeconds(withoutSeconds)); // 37800
কোড ব্যাখ্যা
- ডিফল্ট মান: `(str || '0:0:0')` - null/undefined হ্যান্ডল
- স্প্লিট: `.split(':')` - কোলন দিয়ে ভাগ
- ডিস্ট্রাকচারিং + ডিফল্ট: `[hh='0', mm='0', ss='0']` - মিসিং পার্ট হ্যান্ডল
- পার্সইন্ট: `parseInt(..., 10)` - বেস ১০-এ রূপান্তর (রেডিক্স নির্দিষ্ট করা ভালো প্র্যাক্টিস)
- ফলব্যাক: `|| 0` - NaN হলে ০
- গণনা: `hour*3600 + minute*60 + second`
আউটপুট
86083 // 23*3600 + 54*60 + 43
45000 // 12*3600 + 30*60 + 0
37800 // 10*3600 + 30*60 + 0 (সেকেন্ড ডিফল্ট ০)
আধুনিক ও উন্নত সংস্করণ
১. Regex ভিত্তিক (বাড়তি বৈধতা)
const countSecondsRegex = (str) => {
const match = String(str).match(/^(\d+):(\d+)(?::(\d+))?$/);
if (!match) return NaN;
const [, h, m, s = '0'] = match;
return parseInt(h) * 3600 + parseInt(m) * 60 + parseInt(s);
};
২. Date অবজেক্ট ব্যবহার (ব্রাউজার/Node)
const countSecondsDate = (str) => {
const [h, m, s = 0] = str.split(':').map(Number);
const date = new Date(0, 0, 0, h, m, s);
return date.getTime() / 1000;
};
৩. লক্ষণীয় ফাংশন (Arrow + Destructuring)
const toSeconds = ([h = 0, m = 0, s = 0] = []) =>
h * 3600 + m * 60 + s;
const countSeconds = str => toSeconds((str || '0:0:0').split(':').map(Number));
রিভার্স: সেকেন্ড থেকে HH:MM:SS
const formatDuration = (seconds) => {
const h = Math.floor(seconds / 3600).toString().padStart(2, '0');
const m = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
const s = (seconds % 60).toString().padStart(2, '0');
return `${h}:${m}:${s}`;
};
console.log(formatDuration(86083)); // "23:54:43"
ব্যবহারিক অ্যাপ্লিকেশন
- ভিডিও প্লেয়ার: করেন্ট টাইম / ডিউরেশন
- টাইম ট্র্যাকিং: টাস্ক ডিউরেশন ক্যালকুলেশন
- শিডিউলিং: ক্রন এক্সপ্রেশন পার্সিং
- লগ অ্যানালাইসিস: টাইমস্ট্যাম্প পার্সিং
সারাংশ
ডিস্ট্রাকচারিং অ্যাসাইনমেন্ট এবং ডিফল্ট ভ্যালু ব্যবহার করে রোবাস্ট এবং সংক্ষিপ্ত কোড লেখা যায়। `parseInt(..., 10)` এবং `|| 0` নিশ্চিত করে ইনভ্যালিড ইনপুট হ্যান্ডল হয়।