Skip to content

Instantly share code, notes, and snippets.

@jovey-zheng
Last active July 28, 2016 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jovey-zheng/007b004295ad085575cbe276a545b8c0 to your computer and use it in GitHub Desktop.
Save jovey-zheng/007b004295ad085575cbe276a545b8c0 to your computer and use it in GitHub Desktop.
Format Date.
class DateFormat {
constructor(tmp) {
this.tmp = +tmp || Date.now();
}
duration(format = 'HH:mm:ss') {
let hour = ~~(this.tmp/1000/60/60);
let minutes = ~~((this.tmp/1000/60)%60);
let seconds = ~~((this.tmp/1000)%60);
return format.replace(/HH|mm|ss/g, (reg) => {
switch (reg) {
case 'HH':
return fill(hour);
break;
case 'mm':
return fill(minutes);
break;
case 'ss':
return fill(seconds);
break;
}
});
}
format(format = 'YYYY-MM-DD HH:mm:ss') {
const date = new Date(this.tmp);
return format.replace(/YYYY|MM|DD|HH|mm|ss/g, (reg) => {
switch (reg) {
case 'YYYY':
return fill(date.getFullYear());
break;
case 'MM':
return fill(date.getMonth() + 1);
break;
case 'DD':
return fill(date.getDate());
break;
case 'HH':
return fill(date.getHours());
break;
case 'mm':
return fill(date.getMinutes());
break;
case 'ss':
return fill(date.getSeconds());
break;
}
});
}
}
const fill = (val) => val < 10 ? `0${val}` : val;
export default DateFormat;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment