Skip to content

Instantly share code, notes, and snippets.

@chipoglesby
Last active May 24, 2018 13:36
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 chipoglesby/e312a6f63ca2b60b1269 to your computer and use it in GitHub Desktop.
Save chipoglesby/e312a6f63ca2b60b1269 to your computer and use it in GitHub Desktop.
Custom Date in Javascript - Looks at today's date and pulls a date range from 2 months ago.
//gets Today's date
var currentDate = new Date();
//Pulls the date and month parts of the date out.
var year = currentDate.getFullYear();
var month = getTwoMonthsAgo(currentDate);
//for formatting.
month = padTwo(month);
//All months start at one.
var firstDay = "01";
var yearMonth = year + "" + month;
//string of YYYYMMDD
var startDate = yearMonth + "01";
//Finds the number of days in the target month
var totalDays = new Date(year, month, 0).getDate();
//string of YYYYMMDD
var endDate = yearMonth + totalDays;
returnString = 'CUSTOM_DATE ' + startDate + ', ' + endDate;
return returnString
/*
* @param date object of today's date.
* @return String of Month number of 2 months ago
*/
function getTwoMonthsAgo(date){
var month = date.getMonth();
if(month == 1)
month = 12;
else if(month == 0)
month = 11;
else
month -= 1;
return month;
}
function padTwo(num){
return (num < 10 ? '0' : '') + num;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment