Format Timestamp (timegao,12hour, 24hour)
Fungsi formatTimestamp_hstry digunakan untuk memformat waktu (timestamp) ke beberapa jenis format, seperti:
- 12-hour: Format waktu 12 jam, contoh: 15/08/2024 02:30 PM.
- 24-hour: Format waktu 24 jam, contoh: 15/08/2024 14:30.
- timeago: Format waktu relatif, contoh: 5 minutes ago.
Parameter
- timestamp: Waktu dalam milidetik (contoh: Date.now()).
- format: Jenis format yang diinginkan. Nilai default adalah '12hour'. Pilihan lainnya:
- '24hour'
- 'timeago'
MainScript
Salin kode berikut ke dalam kodemu:
function formatTimestamp_hstry(timestamp, format = '12hour') {
const date = new Date(timestamp);
const now = new Date();
const diffInSeconds = Math.floor((now - date) / 1000);
const day = String(date.getDate()).padStart(2, '0');
const month = String(date.getMonth() + 1).padStart(2, '0');
const year = date.getFullYear();
const hours24 = date.getHours();
const hours12 = hours24 % 12 || 12;
const minutes = String(date.getMinutes()).padStart(2, '0');
const period = hours24 < 12 ? 'AM' : 'PM';
const time24 = `${String(hours24).padStart(2, '0')}:${minutes}`;
const time12 = `${hours12}:${minutes} ${period}`;
switch (format) {
case 'timeago':
if (diffInSeconds < 60) return `${diffInSeconds} seconds ago`;
if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`;
if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`;
if (diffInSeconds < 604800) return `${Math.floor(diffInSeconds / 86400)} days ago`;
if (diffInSeconds < 2419200) return `${Math.floor(diffInSeconds / 604800)} weeks ago`;
return `${Math.floor(diffInSeconds / 2419200)} months ago`;
case '24hour':
return `${day}/${month}/${year} ${time24}`;
case '12hour':
return `${day}/${month}/${year} ${time12}`;
default:
return `${day}/${month}/${year} ${time24}`;
}
}
Contoh Pakai mainScript
formatTimestamp_hstry1: Format 12hour
const formattedTime = formatTimestamp_hstry(Date.now(), '12hour');
console.log(formattedTime); // Output: 15/08/2024 02:30 PM
2: Format 24hour
const formattedTime = formatTimestamp_hstry(Date.now(), '24hour');
console.log(formattedTime); // Output: 15/08/2024 14:30
3: Format timeago
const oneHourAgo = Date.now() - 3600000;
const formattedTime = formatTimestamp_hstry(oneHourAgo, 'timeago');
console.log(formattedTime); // Output: 1 hours ago
Download File!
Komentar
Posting Komentar
Yang Sopan komennya.
apapun yang gak aku suka bakal Kuhilangkan.