Skip to content

Instantly share code, notes, and snippets.

@ridhotegar
Last active December 23, 2021 05:06
Show Gist options
  • Save ridhotegar/996d1ee63a03be36c5312e7c194cbf50 to your computer and use it in GitHub Desktop.
Save ridhotegar/996d1ee63a03be36c5312e7c194cbf50 to your computer and use it in GitHub Desktop.
Formatting date on JS
/*
waktu.add(*{format tanggal}, *{jenis}, *{jumlah penambahan}, {custom date / null})
waktu.add('DD, dd FF YY', 'dd', 1) | waktu.add('DD, dd FF YY', 'dd', 1, '2020-09-25 13:30:00')
waktu.set('dd-MM-YY') | waktu.set('dd/MM/YY H:i:s', '2020-09-25')
*/
var waktu = {
add : (format, jenis, plus, value = null) => {
let d = (value != null) ? new Date(value) : new Date();
if (jenis == 'i') { d.setminutes(d.getMinutes() + plus); }
else if (jenis == 'H') { d = d.setHours(d.getHours() + plus); }
else if (jenis == 'dd') { d = d.setDate(d.getDate() + plus); }
else if (jenis == 'MM') { d = d.setMonth(d.getMonth() + plus); }
else if (jenis == 'YY') { d = d.setFullYear(d.getFullYear()) + plus; }
return waktu.set(format, d);
},
set : (format, value = null) => {
let d = (value != null) ? new Date(value) : new Date();
let list = {
's' : waktu.detik(d),
'i' : waktu.menit(d),
'H' : waktu.jam(d),
'dd' : waktu.tanggal(d),
'DD' : waktu.hari(d),
'D' : waktu.hariSingkat(d),
'MM' : waktu.bulan(d),
'FF' : waktu.namaBulan(d),
'YY' : waktu.tahun(d)
}
$.each(list, function(i,v){
format = format.replace(i, v);
});
return format;
},
detik : (d) => {
let sec = d.getSeconds().toString();
if (sec.length === 1) { sec = '0' + sec; }
return sec;
},
menit : (d) => {
let min = d.getMinutes().toString();
if (min.length === 1) { min = '0' + min; }
return min;
},
jam : (d) => {
let hour = d.getHours().toString();
if (hour.length === 1) { hour = '0' + hour; }
return hour;
},
tanggal : (d) => {
let day = d.getDate().toString();
if (day.length === 1) { day = '0' + day; }
return day;
},
hari : (d) => {
let day = d.getDay();
let hari = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
return hari[day];
},
hariSingkat : (d) => {
let day = d.getDay();
let hari = ['Min', 'Sen', 'Sel', 'Rab', 'Kam', 'Jum', 'Sab'];
return hari[day];
},
bulan : (d) => {
let month = (d.getMonth()+1).toString();
if (month.length === 1) { month = '0' + month; }
return month;
},
namaBulan : (d) => {
let month = d.getMonth();
let bulan = ['Jan', 'Feb', 'Maret','April','Mei','Juni','Juli','Agus','Sep','Okt','Nov','Des'];
return bulan[month];
},
tahun : (d) => {
let year = d.getFullYear();
return year;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment