Last active
August 31, 2018 19:50
-
-
Save dtomasi/3ea4ce1851e9a821ab42722e47dcf5a7 to your computer and use it in GitHub Desktop.
Set of Date-Helper-Functions
This file contains hidden or 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
/** | |
* Get the last full our of given date or now | |
*/ | |
function getPrevFullHour(date) { | |
if (!date) { | |
date = new Date(); | |
} | |
var copiedDate = new Date(date); | |
copiedDate.setMinutes(0); | |
copiedDate.setSeconds(0); | |
return copiedDate; | |
} | |
/** | |
* Get the last our of given date or now | |
*/ | |
function getPrevHour(date) { | |
if (!date) { | |
date = new Date(); | |
} | |
var copiedDate = new Date(date); | |
copiedDate.setHours(date.getHours() - 1); | |
copiedDate.setSeconds(0); | |
return copiedDate; | |
} | |
/** | |
* Get the date count of days ago | |
* optionally: set the day to 00:00:00 | |
*/ | |
function getDaysAgo(daysCount, date, midnight) { | |
if (!daysCount) { | |
daysCount = 7; | |
} | |
if (!date) { | |
date = new Date(); | |
} | |
var copiedDate = new Date(date); | |
copiedDate.setDate(copiedDate.getDate() - daysCount); | |
copiedDate.setSeconds(0); | |
if (midnight === true) { | |
copiedDate.setHours(0); | |
copiedDate.setMinutes(0); | |
} | |
return copiedDate; | |
} | |
// Current | |
var date = new Date(); // | |
console.log('Current Date', date); // Current Date Mon Aug 28 2017 10:36:23 GMT+0200 (CEST) | |
console.log('Previous full hour', getPrevFullHour(date)); // Previous full hour Mon Aug 28 2017 10:00:00 GMT+0200 (CEST) | |
console.log('Previous hour', getPrevHour(date)); // Previous hour Mon Aug 28 2017 09:36:00 GMT+0200 (CEST) | |
console.log('7 days ago', getDaysAgo(7, date)); // 7 days ago Mon Aug 21 2017 10:36:00 GMT+0200 (CEST) | |
console.log('7 days ago at midnight', getDaysAgo(7, date, true)); // 7 days ago at midnight Mon Aug 21 2017 00:00:00 GMT+0200 (CEST) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment