Created
June 15, 2012 19:38
-
-
Save cgravolet/2938360 to your computer and use it in GitHub Desktop.
Takes any input and parses it into a valid time string. Requires moment.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Parses a valid time string from ANY string that is passed to it | |
| * | |
| * @param {string} time | |
| * @return {object} a Date object in a Moment wrapper | |
| * @private | |
| */ | |
| function parseTime(time) { | |
| var ampm, currentDay, hour, minute, timeArray; | |
| ampm = 'am'; | |
| day = moment(); | |
| currentDay = day.format('YYYY-MM-DD'); | |
| time = time.toLowerCase(); | |
| timeArray = time.replace(/[^0-9:\.]+/g, '').split(':'); | |
| hour = Math.round(parseFloat(timeArray[0])); | |
| minute = (timeArray.length > 1 ? | |
| Math.round(parseFloat(timeArray[1])) : 0); | |
| if (hour >= 0) { | |
| if (hour > 23) { | |
| hour = 23; | |
| } | |
| } else { | |
| hour = 0; | |
| } | |
| if (minute >= 0) { | |
| if (minute > 59) { | |
| minute = 59; | |
| } | |
| } else { | |
| minute = 0; | |
| } | |
| if (time.indexOf('p') >= 0 || (hour > 11 && time.indexOf('a') < 0)) { | |
| ampm = 'pm'; | |
| } | |
| if (hour > 12) { | |
| ampm = 'pm'; | |
| } else if (hour < 1) { | |
| ampm = 'am'; | |
| } | |
| return moment(currentDay + ' ' + hour + ':' + minute + ampm, | |
| 'YYYY-MM-DD h:mma'); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment