change time string of HH:mm am/pm to 24 hour time - javascript

I get a variable string like so:
8:45 am
And want, if it is pm, to convert it to 24 hour time. So that I can then drop the am/pm and use it with something else.
I can drop the am/pm quite easily like this:
function replaceEnds(string) {
string = string.replace("am", "");
string = string.replace("pm", "");
return string;
}
But of course if I do that, I don't know if the string is am or pm, so I don't know to add 12 hours on to the string to make it 24 hour.
Anyone know how I could resolve this? I absolutely cannot change the input that I get of the variable, it'll always be the hour (in 12 hour time), minutes, and am or pm.

Using moment.js:
moment(string, 'h:mm a').format('H:mm');
If you want to do it manually, this would be my solution:
function to24Hour(str) {
var tokens = /([10]?\d):([0-5]\d) ([ap]m)/i.exec(str);
if (tokens == null) { return null; }
if (tokens[3].toLowerCase() === 'pm' && tokens[1] !== '12') {
tokens[1] = '' + (12 + (+tokens[1]));
} else if (tokens[3].toLowerCase() === 'am' && tokens[1] === '12') {
tokens[1] = '00';
}
return tokens[1] + ':' + tokens[2];
}
The manual solution is harder to understand, is less flexible, is missing some error checking and needs unit tests. In general, you should usually prefer a well-tested popular library's solution, rather than your own (if a well-tested library is available).

Without using any additional JavaScript libraries:
/**
* #var amPmString - Time component (e.g. "8:45 PM")
* #returns - 24 hour time string
*/
function getTwentyFourHourTime(amPmString) {
var d = new Date("1/1/2013 " + amPmString);
return d.getHours() + ':' + d.getMinutes();
}
So for example:
getTwentyFourHourTime("8:45 PM"); // "20:45"
getTwentyFourHourTime("8:45 AM"); // "8:45"

In case you're looking for a solution that converts ANY FORMAT to 24 hours HH:MM correctly.
function get24hTime(str){
str = String(str).toLowerCase().replace(/\s/g, '');
var has_am = str.indexOf('am') >= 0;
var has_pm = str.indexOf('pm') >= 0;
// first strip off the am/pm, leave it either hour or hour:minute
str = str.replace('am', '').replace('pm', '');
// if hour, convert to hour:00
if (str.indexOf(':') < 0) str = str + ':00';
// now it's hour:minute
// we add am/pm back if striped out before
if (has_am) str += ' am';
if (has_pm) str += ' pm';
// now its either hour:minute, or hour:minute am/pm
// put it in a date object, it will convert to 24 hours format for us
var d = new Date("1/1/2011 " + str);
// make hours and minutes double digits
var doubleDigits = function(n){
return (parseInt(n) < 10) ? "0" + n : String(n);
};
return doubleDigits(d.getHours()) + ':' + doubleDigits(d.getMinutes());
}
console.log(get24hTime('6')); // 06:00
console.log(get24hTime('6am')); // 06:00
console.log(get24hTime('6pm')); // 18:00
console.log(get24hTime('6:11pm')); // 18:11
console.log(get24hTime('6:11')); // 06:11
console.log(get24hTime('18')); // 18:00
console.log(get24hTime('18:11')); // 18:11

I've use something similar to this
//time is an array of [hh] & [mm am/pm] (you can get this by time = time.split(":");
function MilitaryTime(time){
if(time[1].indexOf("AM")!=-1){
//its in the morning, so leave as is
return time;
}else if(time[0]!="12"){
//If it is beyond 12 o clock in the after noon, add twelve for military time.
time[0]=String(parseInt(time[0])+12);
return time;
}
else{
return time;
}
}
Once you get your time returned, you can alter the text in any way you want.

Related

Best way to normalize time in JS

I have some data that's inconsistent. It's all time related but I have some records that shows 3pm others 14:00.
Is there an easy way to normalize that in JS?
Thanks
This function will return you a 24-hour-formatted time
function normaliseTime(time) {
// If there is AM/PM in the string, do conversion
if (time.toUpperCase().indexOf('M') >= 0) {
// Remove the AM/PM text and split the hour and minute
var tmArray = time.replace(/\D/g, '').split(':');
// If PM, add 12 to the hour
if (time.toUpperCase().indexOf('PM') >= 0) {
tmArray[0] = parseInt(tmArray[0]) + 12;
}
// If minutes were not provided (i.e., 3PM), add 00 as minutes
if (tmArray.length < 2) {
tmArray[1] = '00';
}
return tmArray.join(':');
}
// If there was no AM/PM in the input, return it as is
return time;
}

Convert my my variable into a 12/12 time format using moment.js

I need to convert my time that is in military time 24 hours time to regular 12/12 time.
nextArrivalFinal2 = ((hour > 0 ? hour + ":" + (min < 10 ? "0" : "") : "") + min + ":" + (sec < 10 ? "0" : "") + sec);
console.log("nextArrival2", typeof nextArrivalFinal2)
console.log("nextArrival2", nextArrivalFinal2)
var convertedDate = moment(new Date(nextArrivalFinal2));
console.log('converted1', convertedDate)
console.log('converted', moment(convertedDate).format("hh:mm:ss"));
nextArrivalFinal2 displays the time as a string in HH:MM:ss format. But when I plug it into the moment js, it says it is an invalid date.
You are not parsing the time with moment.js, the line:
var convertedDate = moment(new Date(nextArrivalFinal2));
is using the date constructor to parse a string like "13:33:12", which will likely return an invalid date in every implementation (and if it doesn't, it will return something that may be very different to what you expect).
Use moment.js to parse the string and tell it the format, e.g.
var convertedDate = moment(nextArrivalFinal2, 'H:mm:ss'));
Now you can get just the time as:
convertedDate().format('h:mm:ss a');
However, if all you want is 24 hr time reformatted as 12 hour time, you just need a simple function:
// 13:33:12
/* Convert a time string in 24 hour format to
** 12 hour format
** #param {string} time - e.g. 13:33:12
** #returns {sgtring} same time in 12 hour format, e.g. 1:33:12pm
*/
function to12hour(time) {
var b = time.split(':');
return ((b[0]%12) || 12) + ':' + b[1] + ':' + b[2] + (b[0] > 12? 'pm' : 'am');
}
['13:33:12','02:15:21'].forEach(function(time) {
console.log(time + ' => ' + to12hour(time));
});

jqm-calendar time format (24 hour default...would prefer 12 hour)

I am using jqm-calendar for my jquery mobile app. Right now the default time format is 24 hours. I would like to change it to 12 hours.
Thank you.
https://github.com/JWGmeligMeyling/jqm-calendar
In file jw-jqm-cal.js
add this function:
function tConvert (time) {
// Check correct time format and split into components
time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1) { // If time format correct
time = time.slice (1); // Remove full string match value
time[5] = +time[0] < 12 ? ' AM' : ' PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
return time.join (''); // return adjusted time or original string
}
and insert this 2 lines in function plugin.settings.eventHandler.getEventsOnDay(begin, end, function(list_of_events):
beginTime =tConvert(beginTime );
endTime=tConvert(endTime);
EDIT
insert before: timeString = beginTime + "-" + endTime :**
...
beginTime =tConvert(beginTime );
endTime=tConvert(endTime);
timeString = beginTime + "-" + endTime,
...

JavaScript Time Until

I need to do the simplest thing, take an input date/time and write out the hours:minutes:seconds until that time. I haven't been able to figure it out. I even tried using Datejs which is great, but doesn't seem to have this functionality built in.
The time is going to be somewhere in the range of 0 mins -> 20 minutes
Thanks!
Don't bother with a library for something so simple. You must know the format of the input date string whether you use a library or not, so presuming ISO8601 (like 2013-02-08T08:34:15Z) you can do something like:
// Convert string in ISO8601 format to date object
// e.g. 2013-02-08T02:40:00Z
//
function isoToObj(s) {
var b = s.split(/[-TZ:]/i);
return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5]));
}
function timeToGo(s) {
// Utility to add leading zero
function z(n) {
return (n < 10? '0' : '') + n;
}
// Convert string to date object
var d = isoToObj(s);
var diff = d - new Date();
// Allow for previous times
var sign = diff < 0? '-' : '';
diff = Math.abs(diff);
// Get time components
var hours = diff/3.6e6 | 0;
var mins = diff%3.6e6 / 6e4 | 0;
var secs = Math.round(diff%6e4 / 1e3);
// Return formatted string
return sign + z(hours) + ':' + z(mins) + ':' + z(secs);
}
You may need to play with the function that converts the string to a date, but not much. You should be providing a UTC timestring anyway, unless you can be certain that the local time of the client is set to the timezone of the supplied datetime value.
Instead of Date.js, try Moment.js.

jQuery Format Time

I have a jQuery script that receives a string in milliseconds inside a parameter, like this:
params.tweetDate='77771564221';
What I need to do is to create a jQuery function that will be able to format this milliseconds string in a USA time, like 10.00 AM or 10.00 PM.
Is there a jQuery function that is able to do this?
Please help.
Thanks
There is Date object in pure javascript, no jQuery needed.
http://www.javascriptkit.com/jsref/date.shtml
Example:
var time = new Date(params.tweetDate),
h = time.getHours(), // 0-24 format
m = time.getMinutes();
// next just convert to AM/PM format (check if h > 12)
No, there's no jQuery function for this. You can use
JavaScript's own Date object, using the getHours() and getMinutes() functions, handling the AM/PM thing yourself (e.g., hours >= 12 is PM), padding out the minutes with a leading 0 if minutes is less than 10, etc. Also note that if hours is 0, you want to make it 12 (because when using the AM/PM style, you write midnight as "12:00 AM", not "0:00 AM").
DateJS, an add-on library that does a huge amount of date stuff (although sadly it's not actively maintained)
PrettyDate from John Resig (the creator of jQuery)
To use just about any of those, first you have to turn that "milliseconds" value into a Date object. If it's really a "milliseconds" value, then first you parse the string into a number via parseInt(str, 10) and then use new Date(num) to create the Date object representing that point in time. So:
var dt = new Date (parseInt(params.tweetDate, 10));
However, the value you've quoted, which you said is a milliseconds value, seems a bit odd — normally it's milliseconds since The Epoch (Jan 1, 1970), which is what JavaScript uses, but new Date(parseInt("77771564221", 10)) gives us a date in June 1972, long before Twitter. It's not seconds since The Epoch either (a fairly common Unix convention), because new Date(parseInt("77771564221", 10) * 1000) gives us a date in June 4434. So the first thing to find out is what that value actually represents, milliseconds since when. Then adjust it so it's milliseconds since The Epoch, and feed it into new Date() to get the object.
Here is a function for you:
function timeFormatter(dateTime){
var date = new Date(dateTime);
if (date.getHours()>=12){
var hour = parseInt(date.getHours()) - 12;
var amPm = "PM";
} else {
var hour = date.getHours();
var amPm = "AM";
}
var time = hour + ":" + date.getMinutes() + " " + amPm;
console.log(time);
return time;
}
You may call the function in any approach like:
var time = timeFormatter(parseInt("2345678998765"));
take a look at timeago: this is a jquery plugin used exactly for this purposes.
Using T.J.'s solution this is what I ended up with.
var date = new Date(parseInt("77771564221", 10));
var result = new Array();
result[0] = $.datepicker.formatDate('DD, M, d, yy', date);
result[1] = ' ';
if (date.getHours() > 12) {
result[2] = date.getHours() - 12;
} else if (date.getHours() == 0 ) {
result[2] = "12";
} else {
result[2] = date.getHours();
}
result[3] = ":"
result[4] = date.getMinutes();
if (date.getHours() > 12) {
result[5] = " pm";
} else {
result[5] = " am";
}
console.log(result.join(''));

Categories

Resources