4

I've been playing with jquery and I've run myself into a time problem. I've got 3 time input select boxes, one for hours, one for minutes, and one for the Meridian. I need to convert this time into a 24 hour string format and then stick it into a hidden input.

var time = "";
time += $("#EventCloseTimeHour option:selected").text();
time += ":" + $("#EventCloseTimeMin option:selected").text() + ":00";
time += " " + $("#EventCloseTimeMeridian option:selected").text();

$("#ConditionValue").val(time);         

This gives me "1:30:00 pm" where I need "13:30:00". Any quick javascript time tips?

reconbot
  • 5,138
  • 6
  • 45
  • 63
  • I have to add I recently found out about datejs and it's amazing - you should think if you want to include an entire date library for a single problem (like above) but I do a lot of date math so it's more then useful. http://www.datejs.com/ – reconbot Feb 11 '09 at 00:27

5 Answers5

8

Example of tj111 suggestion:

$("#ConditionValue").val(
    (
        new Date(
            "01/01/2000 " + 
            $("#EventCloseTimeHour option:selected").text() +
            $("#EventCloseTimeMin option:selected").text() + ":00" +
            " " +
            $("#EventCloseTimeMeridian option:selected").text()
        )
    ).toTimeString().slice(0,8))
;

Or you can use:

hour = hour %12 + (meridian === "AM"? 0 : 12);
hour = hour < 10 ? "0" + hour : hour;  
Community
  • 1
  • 1
some
  • 48,070
  • 14
  • 77
  • 93
  • I like yours the best so far but I get invalid date out of "toTimeString" and then It slices it up to just say "Invalid ". This is firefox with firebug, but it doesn't work in chrome either. I don't think the date object takes meridians – reconbot Feb 03 '09 at 21:01
  • Check if you get the right values from the jquerys... If the input is invalid you get an invalid output. – some Feb 03 '09 at 21:06
  • @some—please don't recommend parsing with the built-in parser, it's implementation dependent and very error prone, per [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) Also, [*toTimeString*](http://ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.totimestring) is implementation dependent and may not return the required value. – RobG Jul 04 '17 at 07:02
  • Sure @RobG. Do you know where I can find a flux capacitor for my time machine, so that I can go back in time to February 2009 ? – some Jul 04 '17 at 19:10
  • @RobG, I know there is, but... this question was asked almost 8.5 years ago, with no activity until a bot updated the links from http to https about a month ago. I made this answer community wiki, since it was just an example of the method that tj111 suggested. I also show how to calculate the hour without using the date-object.Since it is accepted the person who asked the question was satisfied. Feel free to update this answer if it bothers you that much. :-) – some Jul 05 '17 at 06:52
1

You should look into the native JavaScript Date Object methods.

TJ L
  • 23,914
  • 7
  • 59
  • 77
  • Is there a way to input the Meridian (am/pm)? – reconbot Feb 03 '09 at 20:26
  • If you use the Date.parse method, it accepts AM/PM in the string (but requires a full date in front of it). – TJ L Feb 03 '09 at 20:30
  • it doesn't seem to work with date parse - I keep getting invalid date format – reconbot Feb 03 '09 at 21:04
  • 1
    Try with Date.parse("01/01/2001 12:00 PM"); (There needs to be a space between time time and AM/PM and the date has to be in the format shown) – some Feb 03 '09 at 21:14
  • @some—please don't recommend parsing with the built-in parser, it's implementation dependent and very error prone, per [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Jul 04 '17 at 07:01
  • This isn't an answer, it should be a comment. – RobG Jul 04 '17 at 07:01
  • @RobG You are correct that this would be better as a comment when using the current standard of Stackoverflow. But the site was different 8.5 years ago. It is also possible that tj111 didn't have enough reputation to post a comment back then. – some Jul 05 '17 at 07:02
  • @some—this answer has been linked as a duplicated, so it's not just about the OP. Maybe tj111 has left the building. :-/ – RobG Jul 05 '17 at 23:03
  • Not as active on the answering side, but I still end up here all the time. This was during the alpha or beta days of SO and the standards were a little different back then. I agree it doesn't meet modern standards for an answer. – TJ L Jul 10 '17 at 15:42
1
var time = "";
var hour = Number($("#EventCloseTimeHour option:selected").text())%12 + ($("#EventCloseTimeMeridian option:selected").text() == 'PM'?12:0)) ;


time +=("00"+String(hour)).slice(-2)+":"+ $("#EventCloseTimeMin option:selected").text();

The key to this solution is using the conditional operator "a?b:c" which translates to "if a then b else c"

Michael MacDonald
  • 708
  • 1
  • 6
  • 24
  • Still breaks with 12:xx AM. You always has to mod the time with 12, and then you add 12 if its PM. – some Feb 03 '09 at 21:23
0

Just to add a plain JS answer, the following will format the time based on the length of the initial string. If h:mm returns HH:mm, if h:mm:ss returns HH:mm:ss.

If HH:mm:ss is always required, it's simple to add default seconds of ":00" if not present in initial string.

// Change time in h:mm:ss ap to  HH:mm:ss time
// If time missing seconds, returns HH:mm
function timeToHHmm(time) {
  var nums = time.match(/\d+/g);
  var am   = /am/i.test(time);
  nums[0] = ('0' + ((nums[0]%12) + (am? 0 : 12))).slice(-2);
  // If HH:mm:ss required, use following line instead of last
  // return nums.join(':') + (nums.length == 2? ':00' : '');
  return nums.join(':');
}

// Some tests
['2:45am',     // hh:mm only
 '5:15:45pm',  // hh:mm:ss
 '5:15:45 pm', // space before am/pm
 '05:15:45 pm',// leading zero on hour
 '12:02am',
 '12:02 pm',
 '12:02:00am'
 ].forEach(function(time) {
  console.log(time + ' => ' + timeToHHmm(time));
});
RobG
  • 142,382
  • 31
  • 172
  • 209
0

I got it with a few people's answers.

var time = "";
var hour = Number($("#EventCloseTimeHour option:selected").text());
if($("#EventCloseTimeMeridian option:selected").text() == 'PM'){
    hour = String((hour%12) + 12);
}
hour = hour < 10 ? "0" + hour : hour;
time +=hour+":"+ $("#EventCloseTimeMin option:selected").text() + ":00";
reconbot
  • 5,138
  • 6
  • 45
  • 63