Last active
November 8, 2019 06:46
-
-
Save imbdb/9772a80a35e48eded49eea36437c0155 to your computer and use it in GitHub Desktop.
Takes a native date object and returns string containing date the specified format
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
/* | |
Takes a native date object and returns string containing date the specified format | |
Format segments are | |
{{dd}} - 2 digit date | |
{{D}} - Day of week | |
{{mm}} - 2 digit month | |
{{mmm}} - 3 letter month | |
{{MMM}} - Full month | |
{{yyyy}} - 4 digit year | |
{{H}} - 2 digit hour (24 hours) | |
{{h}} - 2 digit hour (12 hours) | |
{{i}} - 2 digit minutes | |
{{a}} - am or pm | |
{{A}} - AM or pm | |
*/ | |
function get_formatted_date(date_obj,format){ | |
var req_format = format||"{{mmm}} {{dd}}"; | |
var t = "am"; | |
if(typeof(date_obj)=="undefined"){return "";} | |
if(date_obj.toString() == "Invalid Date"){return "";} | |
var required_functions = ["getDate","getMonth"]; | |
for (var i = required_functions.length - 1; i >= 0; i--) { | |
if(typeof(date_obj[required_functions[i]])=="undefined"){return "";} | |
} | |
var months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; | |
var months_full = ["January","February","March","April","May","June","July","August","September","October","November","December"]; | |
var days = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]; | |
req_format = req_format.replace(/\{\{mmm\}\}/g, months[date_obj.getMonth()]); | |
req_format = req_format.replace(/\{\{MMM\}\}/g, months_full[date_obj.getMonth()]); | |
req_format = req_format.replace(/\{\{mm\}\}/g, ("0"+(date_obj.getMonth() + 1)).slice(-2)); | |
req_format = req_format.replace(/\{\{dd\}\}/g, ("0"+date_obj.getDate()).slice(-2)); | |
req_format = req_format.replace(/\{\{D\}\}/g, days[date_obj.getDay()]); | |
req_format = req_format.replace(/\{\{yyyy\}\}/g, date_obj.getFullYear()); | |
req_format = req_format.replace(/\{\{H\}\}/g, ("0" + date_obj.getHours()).slice(-2)); | |
req_format = req_format.replace(/\{\{h\}\}/g, date_obj.getHours() > 12 ? date_obj.getHours() - 12 : date_obj.getHours() == 0 ? "12" : date_obj.getHours()); | |
req_format = req_format.replace(/\{\{i\}\}/g, ("0" + date_obj.getMinutes()).slice(-2)); | |
if(date_obj.getHours() > 12){t = "pm"} | |
req_format = req_format.replace(/\{\{a\}\}/g, t); | |
req_format = req_format.replace(/\{\{A\}\}/g, t.toUpperCase()); | |
return req_format; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment