0

Some random JS functions.

Free lines JavaScript 1 revisions 83 5 months ago 5 months ago
// Formats a number using the current locale (to handle the 1000's separator).
function numberToLocaleString(value) {
	var localeString = Math.round(parseFloat(value + '')).toLocaleString();
	return localeString.substring(0, localeString.indexOf('.'));
}

function padLeft(number, length) {
	var str = '' + number;
	while (str.length < length) {
		str = '0' + str;
	}
	return str;
}

// Returns the number of milliseconds between 2 date-times represented as strings.
function msBetween(startTime, endTime) {
	return startTime > endTime ? msBetween(endTime, startTime) : parseDateTime(endTime) - parseDateTime(startTime);
}

var dateFormat = /(\d{4})-(\d{2})-(\d{2})[T](\d{2}):(\d{2}):(\d{2})/
// Parses a date-time string and returns a Date (i.e. number of milliseconds)
function parseDateTime(value) {
	if (!value) {
		return 0;
	}
	var match = dateFormat.exec(value)
	if (!match) {
		return 0;
	}
	return Date.parse(match[1] + '/' + match[2] + '/' + match[3] + ' ' + match[4] + ':' + match[5] + ':' + match[6])
}

// Parses just the date portion of a date-time string and returns a Date
function parseDate(value) {
	if (!value) {
		return 0;
	}
	var match = dateFormat.exec(value)
	if (!match) {
		return 0;
	}
	return Date.parse(match[1] + '/' + match[2] + '/' + match[3])
}

var durationFormat = /P((\d+)D)?T((\d+)H)?((\d+)M)?(\d+)S/
// Convert a string of the form P10DT1H15M40S to a count of milliseconds
function parseDurationToMs(value) {
	var match = durationFormat.exec(value)
	if (!match) {
		return 0
	}
	var days = parseInt(match[2] || '0');
	var hrs = parseInt(match[4] || '0');
	var mins = parseInt(match[6] || '0');
	var secs = parseInt(match[7] || '0');
	return ((((((days * 24) + hrs) * 60) + mins) * 60) + secs) * 1000;
}

// Converts milliseconds to days
function msToDays(ms) {
	return (ms / 1000 / 60 / 60 / 24);
}
function daysToMs(days) {
	return (days * 24 * 60 * 60 * 1000);
}

// Formats a number of milliseconds as h:mm:ss
function formatDurationMs(value) {
	var ms = parseInt(value);
	var secs = ms / 1000;
	var mins = secs / 60;
	var hrs = Math.floor(mins / 60);
	mins = Math.floor(mins % 60);
	secs = Math.floor(secs % 60);
	return hrs + ':' + padLeft(mins, 2) + ':' + padLeft(secs, 2);
}

// Converts a millisecond timestamp to a day and month string
function dateToDayAndMonth(ms, dayOffset) {
	var adjustedDate = new Date(ms + (dayOffset * 24 * 60 * 60 * 1000));
	return padLeft(adjustedDate.getMonth() + 1, 2) + "-" + padLeft(adjustedDate.getDate(), 2);
}

// Takes a millisecond timestamp and returns a new millisecond timestamp
function dateFloor(ms) {
	var dt = new Date(ms);
	return Date.parse(dt.getFullYear() + '/' + (dt.getMonth() + 1) + '/' + dt.getDate());
}