Skip to content

Instantly share code, notes, and snippets.

@jhyland87
Created September 6, 2016 21:51
Show Gist options
  • Save jhyland87/00a644f129af272f239621a0eb47d372 to your computer and use it in GitHub Desktop.
Save jhyland87/00a644f129af272f239621a0eb47d372 to your computer and use it in GitHub Desktop.
var Utils = {
//...
/**
* Convert a date/timestamp to an epoch timestamp
*
* @param {Date|string} date Either a date in string format, or a Date object
* @param {string} round Since the date inputs are day specific (no hour/minute/second),
* this dictates if it will be rounded up or down. Allowed values are "start", "stop", "up" and "down"
* @param {string} dateFormat Dates input format (default is "mm/dd/yy")
* @returns {string} Returns the timestamp in epoch format
* @examples
* Utils.convertToEpoch( '08/03/2016' ) // 1470207600
* Utils.convertToEpoch( '08/03/2016', 'up' ) // 1470294000
* Utils.convertToEpoch( '08/03/2016', 'down' ) // 1470121200
* Utils.convertToEpoch( '08/2016/03', 'down', "mm/yy/dd" ) // 1470121200
*/
convertToEpoch: function( date, round, dateFormat ){
var dFormat = ( typeof dateFormat === 'string' ? dateFormat : "mm/dd/yy" ),
GMT = true,
date_day,
dDate
// If the date provided isn't a string or already a date, then throw an error
if( $.inArray( date.constructor.name, [ 'Date', 'String' ] ) === -1 ){
throw "convertToEpoch expected the date parameter to be a String or Date - received: " + date.constructor.name
}
// If its a string, then try to convert it to a date using the datepickers parseDate
else if( date.constructor.name === 'String' ){
dDate = $.datepicker.parseDate( dFormat, date )
}
// Only other scenario is that date is already a Date object, so just use it
else {
dDate = date
}
if( round === 'start' || round === 'down' )
date_day = dDate.getUTCDate()-1
else if( round === 'stop' || round === 'up' )
date_day = dDate.getUTCDate()+1
else
date_day = dDate.getUTCDate()
//date_day = dDate.getUTCDate()
if(GMT){
var x = parseInt(Date.UTC(dDate.getUTCFullYear(),dDate.getUTCMonth(),date_day,dDate.getUTCHours(),dDate.getUTCMinutes(),dDate.getUTCSeconds(),dDate.getUTCMilliseconds())/1000)
return x
} else {
var x = ( dDate.getTime()-dDate.getMilliseconds() )/1000
// x += dDate.getTimezoneOffset();
return x
}
}
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment