Last active
February 1, 2019 13:35
-
-
Save alexpilugin/8ee0a50cb7fd1dd53e1a1d345049d271 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//@returns String | |
function getFormatedDate(formating, date) { | |
const format = formating || 'DD MMM YYYY'; | |
const days = ["Sun", "Mon", "Tue", "We", "Thu", "Fri", "Sat"]; | |
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; | |
function parse(str) { | |
var time = new Date(date); | |
return isNaN(time.getTime()) ? null : time; | |
} | |
var now; | |
if (date instanceof Date) { | |
now = date | |
} else if (typeof (date) == 'string') { | |
const time = parse(date); | |
if (!time) { | |
now = new Date(); | |
} else { | |
now = time | |
} | |
} else { | |
now = new Date(); | |
} | |
var year = now.getFullYear(); | |
var month = now.getMonth() + 1; | |
var currDate = now.getDate(); | |
var monthName = monthNames[now.getMonth()]; | |
var dayOfWeek = days[now.getDay()]; | |
var map = { | |
YYYY: year, | |
YY: year.toString().substr(2, 2), | |
MMM: monthName, | |
MM: ("0" + month).slice(-2), | |
M: month, | |
DD: ("0" + currDate).slice(-2), | |
D: currDate, | |
dddd: dayOfWeek | |
}; | |
return format.replace(/Y+|M+|D+|d+/g, function (str) { | |
return map[str]; | |
}); | |
}; | |
getFormatedDate(); //"01 Feb 2019" | |
getFormatedDate('YYYY-MM-DD'); //"2019-02-01" | |
getFormatedDate('YYYY/MM/DD', new Date()); //"2019/02/01" | |
getFormatedDate('DD MMM YYYY', new Date('2000-02-01')); //"01 Feb 2000" | |
getFormatedDate('dddd DD MMM YY'); //"Fri 01 Feb 19" | |
getFormatedDate('dddd DD MMM YYYY'); //"Fri 01 Feb 2019" | |
getFormatedDate(null, '2010/02/01'); //"01 Feb 2010" | |
getFormatedDate(null, '2010-02-01'); //"01 Feb 2010" | |
getFormatedDate('dddd DD MMM YYYY', '02-01-2010'); //"Mon 01 Feb 2010" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment