Skip to content

Instantly share code, notes, and snippets.

@anddoutoi
Created February 13, 2012 11:44
Show Gist options
  • Save anddoutoi/1816254 to your computer and use it in GitHub Desktop.
Save anddoutoi/1816254 to your computer and use it in GitHub Desktop.
Function that parses stuff to milliseconds
/* inspiration from Jan-Marten de Boer´s Time.js, https://github.com/johmanx10/Time.js */
var ms = (function () {
'use strict';
var second = 1000,
minute = second*60,
hour = minute*60,
day = hour*24,
//week = day*7,
//year = second*3.154e7,// According to Wolfram|Alpha
//month = ~~(year/12), // ~~ == parseInt
typeOf,
parse;
typeOf = (function ( classNames ) {
// a better typeof
var className, i, classTypeMap;
classNames = classNames.replace(/\s+/g, ' ').split(' ');
i = classNames.length;
classTypeMap = {};
while ( ( className = classNames[--i] ) ) {
classTypeMap[ '[object ' + className + ']' ] = className.toLowerCase();
}
return function ( o ) {
if ( 0 === arguments.length ) {
o = this;
}
return null == o ? o + '' : classTypeMap[Object.prototype.toString.call( o )] || 'object';
};
} ('Date Number String'));// Arguments Array Boolean Date Function Number RegExp String
parse = (function () {
var re = /(\d+)(d|h|min|s|ms)/g,
fn = {
'd': function ( i ) {
return i * day;
},
'h' : function ( i ) {
return i * hour;
},
'min' : function ( i ) {
return i * minute;
},
's' : function ( i ) {
return i * second;
},
'ms' : function ( i ) {
return 1 * i;
}
};
return function ( s ) {
var ms = Date.parse( s ),
match, value, unit;
if ( isNaN(ms) ) {
s = s.replace(/\s+/g, '');
ms = 0;
while ( null != (match = re.exec(s)) ) {
value = match[1];
unit = match[2];
ms += fn[unit] && ~~fn[unit]( value );// ~~ == parseInt
}
}
return ms;
};
} ());
return function ( o ) {
var ms;
// o could be of type Date, Number or String
// String can be either something that is parsable by Date.parse OR a string with SI units and non-SI
// units accepted for use with the SI, see http://en.wikipedia.org/wiki/Non-SI_units_mentioned_in_the_SI
//
// e.g. '1h 30min 30s' == 1 hour, 30 minutes and 30 seconds
// whitespace is not required -> '1h30min30s' also works
//o = new Date(2012, 0, 23, 15, 20, 0, 0);
switch ( typeOf(o) ) {
case 'string':
ms = parse( o );
break;
case 'date':
ms = o - new Date();
break;
case 'number':
ms = o;
break;
default:
// throw 'Not valid input';
}
return Math.max(0, ms);
};
} ());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment