convertible-js
Version:
Convert 12-hour time string to 24-hour time and vice versa with flexible formatting.
85 lines (84 loc) • 3.03 kB
JavaScript
;
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var constants_1 = require("./constants");
var RegexPatterns = __importStar(require("./regex-patterns"));
var addLeadingZero = function (time) {
// adding leading zero to hours and minutes if it's not two-digit
if (time && Number(time) < 10) {
return "0" + time;
}
// if time is a falsy value ("" or 0)
if (!time) {
return '00';
}
return "" + time;
};
exports.customTimeFormat = function (_a, desiredFormat) {
var hours = _a.hours, minutes = _a.minutes, period = _a.period;
// => /hh/gi means all occurence of hh (/g) regardless of the casing (/i)
var time = desiredFormat
.replace(/hh/gi, addLeadingZero(hours))
.replace(/h/gi, hours.toString())
.replace(/mm/gi, addLeadingZero(minutes))
.replace(/m/gi, minutes.toString());
// replace time period only if it exists
if (period) {
period = RegexPatterns.AM.test(period) ? constants_1.AM : constants_1.PM;
var upperCasePeriod = period ? period.toUpperCase() : '';
var lowerCasePeriod = period ? period.toLowerCase() : '';
time = time.replace(/A/g, upperCasePeriod).replace(/a/g, lowerCasePeriod);
}
return time;
};
exports.defaultTimeFormat = function (_a) {
var hours = _a.hours, minutes = _a.minutes, period = _a.period, secondsAndMilleseconds = _a.secondsAndMilleseconds;
var time = addLeadingZero(hours) + ":" + addLeadingZero(minutes) + secondsAndMilleseconds;
if (period) {
// add space before it so that 12-hour time is formatted like this hh:mm A
time = time + " " + period;
}
return time;
};
exports.getHoursFrom12HoursTime = function (hours, period) {
if (!period) {
return hours;
}
hours = Number(hours);
// if period is PM and hours is < 12, add 12 hours
if (RegexPatterns.PM.test(period) && hours < 12) {
hours = hours + 12;
}
// if time period is AM and hours is === 12, deduct 12 since 12AM is 00 in 24 hour
if (RegexPatterns.AM.test(period) && hours === 12) {
hours = hours - 12;
}
return hours;
};
exports.getHoursFrom24HoursTime = function (hours) {
hours = Number(hours);
// hours is > 13
if (hours >= 13) {
hours = hours - 12;
}
if (hours === 0) {
hours = hours + 12;
}
return hours;
};
// time period is AM/PM
exports.getTimePeriodFrom24HourTime = function (hours) {
hours = Number(hours);
// if period is PM and hours is < 12, add 12 hours
if (hours < 12) {
return constants_1.AM;
}
// if time period is AM and hours is === 12, deduct 12 since 12AM is 00 in 24 hour
return constants_1.PM;
};