Skip to content

Instantly share code, notes, and snippets.

@rafaelfaria
Created January 24, 2017 22:22
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 rafaelfaria/b6b3abfd2a9f662a6e8cc0ae92bbc3f2 to your computer and use it in GitHub Desktop.
Save rafaelfaria/b6b3abfd2a9f662a6e8cc0ae92bbc3f2 to your computer and use it in GitHub Desktop.
var startTime = new Date();
function dateFormat(timestamp, currentDateFormat, timeSinceFormat) {
// Format string timestamps to enforce a number unless it's not passed
// as a human readable format. Ex: '1484897633537'.
timestamp = isNaN(Number(timestamp)) ? timestamp : Number(timestamp);
// Month and weekdays
let listMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let nowDate = new Date(), // will be used to get the elapsed time
timestampDate = new Date(timestamp);
/*
* @method removeLeadingZero
* Removes the leading 0 of a number. Ex (01 to 1, 05 to 5)
* @param num {number} - The number to be converted
* @returns {number} The converted number
*/
let removeLeadingZero = function(num) {
num = '' + num;
return (num.indexOf('0') == 0 && num != '0') ? num.substring(1) : num;
}
/*
* @method addLeadingZero
* Adds the leading 0 to a number that only has one digit. Ex (1 to 01, 5 to 05)
* @param num {number} - The number to be converted
* @returns {number} The converted number
*/
let addLeadingZero = function(num) {
num = Number(num);
return isNaN(num) ? '00' : (((num < 10) ? '0' : '') + num);
}
/*
* @method getAMPM
* @param hours {number} - The timestamp hour
* @returns {string} the AM/PM according to the hour
*/
let getAMPM = function(hours) {
if (Number(hours) > 11) {
return 'PM';
}
return 'AM';
}
/*
* @method getOrdinal
* @param num {number} - the number to calculate the ordinal (st, nd, rd, th)
* @returns {string} the ordinal
*/
let getOrdinal = function(num) {
if (num>3 && num<21) return 'th';
switch (num % 10) {
case 1: return "st";
case 2: return "nd";
case 3: return "rd";
default: return "th";
}
}
/*
* @method convert24HoursIn12
* @param hours {number} - The timestamp hour
* @returns {number} The hour converted in 12 hour format
*/
let convert24HoursIn12 = function(hours) {
let convertedHour = hours;
if (hours == 0) {
convertedHour = 12;
}
if (hours > 12) {
convertedHour = hours - 12;
}
return convertedHour;
}
/*
* @method getElapsedMin
* @returns {number} Get the elapsed number of minutes passed from the timestamp to now
*/
let getElapsedMin = function() {
return Math.floor((nowDate - timestampDate) / 1000 / 60);
}
/*
* @method getElapsedMin
* @returns {number} Get the elapsed number of hours passed from the timestamp to now
*/
let getElapsedHours = function() {
return Math.floor((nowDate - timestampDate) / 1000 / 60 / 60);
}
/*
* @method convert24HoursIn12
* @param hours {number} - The timestamp hour
* @returns {number} The hour converted in 12 hour format
*/
let getElapsedTime = function() {
let elapsedHours = getElapsedHours(),
elapsedMin = getElapsedMin(),
elapsedTime;
// Format the elapsed time (X m ago or X h ago)
if (elapsedHours < 1) {
elapsedTime = removeLeadingZero(elapsedMin) + 'm ago';
} else {
elapsedTime = removeLeadingZero(elapsedHours) + 'h ago';
}
return elapsedTime;
}
/*
* @method constructDateParts
* Creates an object with all the parts of the time in order to make the format replacement
* @param timestampDate {Date} - The timestamp date to be formated
* @returns {Object}
*/
let constructDateParts = function(timestampDate) {
let hours = timestampDate.getHours(),
date = timestampDate.getDate(),
minutes = timestampDate.getMinutes();
return {
month: addLeadingZero(timestampDate.getMonth() + 1),
date: addLeadingZero(date),
dateOneDigit: removeLeadingZero(date),
year: addLeadingZero(timestampDate.getFullYear()),
ampm: getAMPM(hours),
day: timestampDate.getDay(),
hour24: addLeadingZero(hours),
hour24OneDigit: removeLeadingZero(hours),
hour12: addLeadingZero(convert24HoursIn12(hours)),
hour12OneDigit: removeLeadingZero(convert24HoursIn12(hours)),
minutes: addLeadingZero(minutes),
minutesOneDigit: removeLeadingZero(minutes),
ordinal: getOrdinal(date),
elapsedHour: getElapsedHours(),
elapsedTime: getElapsedTime()
};
}
/*
* @method datePatternReplace
* Replaces the strings looking for the matching date formats and replace them with value based on the timestamp
* @param dateFromatStr {string} - The string to be formatted. Ex: HH:ii - DD:MM
* @returns {string} The formated string with the date format replacements
*/
let datePatternReplace = function(dateFromatStr) {
let weekDay = weekdays[dateParts.day], // Tuesday
weekDayMid = weekDay.substring(0, 3), // Tue
weekDayShort = weekDay.substring(0, 2), // Tu
monthLong = listMonths[Number(dateParts.month) - 1], // June
monthShort = monthLong.substring(0, 3), // Jun
yearShort = dateParts.year.substring(2), // 17 (2017)
amPmLowercase = dateParts.ampm.toLowerCase(); // am/pm
// Execute the replacement and format the date/time
dateFromatStr = dateFromatStr
// AM/PM - am/pm
.replace(/AA/g, dateParts.ampm)
.replace(/aa/g, amPmLowercase)
// Hours (24)
.replace(/HH/g, dateParts.hour24)
.replace(/H/g, dateParts.hour24OneDigit)
// Hours (12)
.replace(/hh/g, dateParts.hour12)
.replace(/h/g, dateParts.hour12OneDigit)
// Minutes
.replace(/II/g, dateParts.minutes)
.replace(/I/g, dateParts.minutesOneDigit)
// Date
.replace(/DD/g, dateParts.date)
.replace(/D/g, dateParts.dateOneDigit)
// Ordinal for date
.replace(/O/g, dateParts.ordinal)
// Year
.replace(/YYYY/g, dateParts.year)
.replace(/YY/g, yearShort)
// Elapsed time (Hours and Minutes)
.replace(/GG/g, dateParts.elapsedTime)
// Month
.replace(/MM/g, monthLong)
.replace(/M/g, monthShort)
// Week day
.replace(/EEEE/g, weekDay)
.replace(/EEE/g, weekDayMid)
.replace(/EE/g, weekDayShort);
return dateFromatStr;
}
// Get the object with date formats
let dateParts = constructDateParts(timestampDate)
// Get the formatted string based on the elapsed
let formatedString = '';
// If the elapsedHours is within 24 hours and the timeSinceFormat is defined
if (dateParts.elapsedHours < 24 && timeSinceFormat) {
formatedString = datePatternReplace(timeSinceFormat);
} else {
formatedString = datePatternReplace(currentDateFormat);
}
return formatedString;
}
//let t = 'Fri Jan 24 2017 13:50:28 GMT+1100 (AEDT)';
let t = '1484897633537';
console.log(dateFormat(t, 'DD M', 'GG'));
console.log(dateFormat(t, 'EEE, DD M'));
console.log(dateFormat(t, 'DDO M YY HH:II'));
console.log(dateFormat(t, 'h:Iaa'));
console.log(dateFormat(t, 'GG'));
/*
AA - AM/PM
aa - am/pm
HH - hours (24) - 2 digits
H - hours (24) - 1 digit
hh - hours (12) - 2 digits
h - hours (12) - 1 digit
II - minutes - 2 digits
I - minutes - 1 digit
DD - date - 2 digits
D - date - 1 digit
O - date - ordinal
MM - month - Long name
M - month - Short name
EEEE - week - long name
EEE - week - 3 letters name
EE - week - 2 letters name
YYYY - year - Long
YY - year - Short
GG - elapse min/hours
*/
// later record end time
var endTime = new Date();
// time difference in ms
var timeDiff = endTime - startTime;
timeDiff /= 1000;
console.log(timeDiff);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment