I want to convert time data to the format HH:mm:ss in JavaScript.
I've got a problem in my code (see comments inside the code):
function parseTime(timeString){
var timeString = timeString.toLowerCase();
timeString = $.trim(timeString);
var regEx = /^([0-9]|1[0-9]|2[0-3])$/;
var regEx2 = /^([0-9]|1[0-9]|2[0-3])\.?([0-5][0-9])$/;
var regEx3 = /^([0-9]|1[0-2])(a|p|am|pm)$/;
var regEx4 = /^([1-9]|10|11|12)\.?([0-5][0-9])(a|p|am|pm)$/;
if(regEx.test(timeString)){
var hours = timeString;
if(hours.length == 1){
hours = '0' + hours;
}
return hours + ':00:00';
}
else if(regEx2.test(timeString)){
var hoursEndIndex, minutesStartIndex;
if(timeString.indexOf('.')){
hoursEndIndex = timeString.indexOf('.');
minutesStartIndex = timeString.indexOf('.') + 1;
}else if(timeString.length == 3){//Problem here timeString.length returns 3 but the code below isn't executed?
hoursEndIndex = 1;
minutesStartIndex = 1;
}else if(timeString.length == 4){//Same thing here?
hoursEndIndex = 2;
minutesStartIndex = 2;
return timeString.length;
}
var hours = timeString.substring(0, hoursEndIndex);
if(hours.length == 1){
hours = '0' + hours;
}
var minutes = timeString.substr(minutesStartIndex, 2);
return hours + ':' + minutes + ':00';
}
I think you are using indexOf incorrectly here:
if(timeString.indexOf('.')){
From the documentation:
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
Probably you mean this:
if(timeString.indexOf('.') > -1) {
With your code the expression in the first if statement will be true even if the string does not contain a dot. This means that the else if statement will never be executed.
I want to convert a almost any kind of time format to the format HH:mm:ss in javacript
Check this out: http://www.datejs.com/
There's no reason to re-invent the wheel.
However, if you are required to implement this yourself, then I believe Mark's solution will help
You're using else if, which requires that all preceding conditional blocks equate to false.
Try this:
if(timeString.indexOf('.')){
hoursEndIndex = timeString.indexOf('.');
minutesStartIndex = timeString.indexOf('.') + 1;
}
if(timeString.length == 3){
hoursEndIndex = 1;
minutesStartIndex = 1;
} else if(timeString.length == 4){
hoursEndIndex = 2;
minutesStartIndex = 2;
return timeString.length;
}
Perhaps you should use captured groups instead of parsing the string again:
var groups = regEx2.exec(timeString);
if(groups){
var hours = groups[0];
if(hours.length == 1){
hours = '0' + hours;
}
var minutes = groups[1];
return hours + ":" + minutes + ":00";
}
Related
I am trying to write a bit of JS code to validate a time entered into an input field in the 24hr format. I would like to be able to detect HH:MM, HHMM and HMM and reject anything else. I also would like to detect if the time is possible withing 24hrs - e.g. to reject 26:70 and the likes and this is what I currently don't manage to do:
function validateTime(rawtime) {
var timeregex = new RegExp('([01]?[0-9]|2[0-3]):[0-5][0-9]');
var timeregex4 = new RegExp('([01]?[0-9]|2[0-3])[0-5][0-9]');
var timeregex3 = new RegExp('[0-9][0-5][0-9]');
var numeric = new RegExp('^[0-9]+$');
if (numeric.test(rawtime))
{
if ((rawtime.length == 4) && (timeregex4.test(rawtime))){
document.getElementById("fdbk").innerHTML ="time with 4 digits";
}
else if ((rawtime.length == 3) && (timeregex3.test(rawtime))){
document.getElementById("fdbk").innerHTML ="time with 3 digits";
}
}
else if (timeregex.test(rawtime)) {
document.getElementById("fdbk").innerHTML ="time with :";
}
}
Jsbin Example
Not too sure what the problem is, it's easy ^_^
var timeregex = /^([01]?[0-9]|2[0-3]):?([0-5][0-9])$/;
Now match it...
var match = rawtime.match(timeregex);
And you get...
var hours = parseInt(match[1],10),
minutes = parseInt(match[2],10);
Done?
Heres a simple function (not using RegEx) that validates the time formats you've requested.
function valTime(time) {
var len = time.length,
hour,
mins;
if(len == 5) { //HH:MM
var spl = time.split(':');
if(!$.isArray(spl)) { return false; } //Not an array
hour = spl[0];
mins = spl[1];
}
if(len == 4) { //HHMM
hour = time[0] + time[1];
mins = time[2] + time[3];
}
if(len == 3) { //HMM
hour = time[0];
mins = time[1] + time[2];
}
if(+hour <= 23 && +mins <= 59) {
return true;
} else {
return false;
}
}
I have a problem with some code I have been producing in JavaScript. I want to calculate the difference between two times on a 24 hour clock. The data comes from two input time fields:
<input type="time" id="start" />
<input type="time" id="end" />
Because of this the times come in a string 00:00, which doesn't help for number calculations.
The way I worked it out was to minus the start from the end. This works perfectly if the the end time is greater, however if the end time is past 11:00 (00:00), I end up with a negative number. I have tried adding 24 to the result if the end is lower than the start but I still get a negative number. This may seem like a dumb question but I was never that good at maths.
var numHours;
if(time_end < time_start){
numHours = parseInt(t_e.substring(0,2)) - parseInt(t_s.substring(0,2)) + 24;
}else{
numHours = parseInt(t_e.substring(0,2)) - parseInt(t_s.substring(0,2));
}
There is probably (definitely) a better way of doing this but how can I get this to work. Also could I calculate the minutes as well to get more accurate time difference.
The solutions provided aren't accounting for the day boundary effectively. And all of this assumes the difference is less than 24 hours. Meaning that we have an upper boundary on the difference between start and end of 23 hours and 59 minutes, otherwise we are confused by the result. But remember that as described a real use case is that an event starts at 11pm and ends at 1am (from 23:00 to 1:00) and the difference is 2 hours NOT 22 hours.
function calculateTime(e) {
var startTime = $('#start').val();
var endTime = $('#end').val();
var startTimeArray = startTime.split(":");
var startInputHrs = parseInt(startTimeArray[0]);
var startInputMins = parseInt(startTimeArray[1]);
var endTimeArray = endTime.split(":");
var endInputHrs = parseInt(endTimeArray[0]);
var endInputMins = parseInt(endTimeArray[1]);
var startMin = startInputHrs*60 + startInputMins;
var endMin = endInputHrs*60 + endInputMins;
var result;
if (endMin < startMin) {
var minutesPerDay = 24*60;
result = minutesPerDay - startMin; // Minutes till midnight
result += endMin; // Minutes in the next day
} else {
result = endMin - startMin;
}
var minutesElapsed = result % 60;
var hoursElapsed = (result - minutesElapsed) / 60;
alert ( "Elapsed Time : " + hoursElapsed + ":" + (minutesElapsed < 10 ?
'0'+minutesElapsed : minutesElapsed) ) ;
}
And I didn't check, but I believe you could just do this, but I'm not checking it :
var result = endMin - startMin;
if (result < 0 ) result = (24*60) + result;
A simple solution that might work best for this limited use-case is to convert both times into total minutes since the start of the day, and then subtract.
Pseudocode:
startMin = startInputHrs * 60 + startInputMin
endMin = endInputHrs * 60 + endInputMin
timeDifference = endMin - startMin
It's up to you how you want to handle a negative result. Maybe give the user an error message, and tell them that the start time has to come before the end time?
I'm a beginner, and some whiz is probably going to come up with an answer in like 2 lines :), but here it is.....this works. input is a string in the form of "1:20pm-2:30am".
function CountingMinutesI(str) {
split = str.split('-')
startTime = split[0]
endTime = split[1]
// for end time
if (endTime === '12:00am') { endInMinutes = 0}
else if (endTime.charAt(endTime.length-2) === 'a') {
if (endTime.substr(0, 2) === '12') {
endInMinutes = parseInt(endTime.split(':')[1].replace(/[a-z]/gi, ''))
}
else {
endHours = endTime.split(':')[0]
endMins = endTime.split(':')[1].replace(/[a-z]/gi, '')
endInMinutes = (parseInt(endHours)*60) + parseInt(endMins)
}
}
else if (endTime === '12:00pm') {endInMinutes = 720}
else {
endHours = endTime.split(':')[0]
endMins = endTime.split(':')[1].replace(/[a-z]/gi, '')
endInMinutes = (parseInt(endHours)*60 + 720) + parseInt(endMins)
}
// for start time
if (startTime === '12:00am') { startInMinutes = 0}
else if (startTime.charAt(startTime.length-2) === 'a') {
if (startTime.substr(0, 2) === '12') {
startInMinutes = parseInt(startTime.split(':')[1].replace(/[a-z]/gi, ''))
}
else {
startHours = startTime.split(':')[0]
startMins = startTime.split(':')[1].replace(/[a-z]/gi, '')
startInMinutes = (parseInt(startHours)*60) + parseInt(startMins)
}
}
else if (startTime.substr(0,2) === '12') {startInMinutes = 720 + parseInt(startTime.split(':')[1].replace(/[a-z]/gi, ''))}
else {
startHours = startTime.split(':')[0]
startMins = startTime.split(':')[1].replace(/[a-z]/gi, '')
startInMinutes = (parseInt(startHours)*60 + 720) + parseInt(startMins)
}
if (endInMinutes > startInMinutes) {output = endInMinutes - startInMinutes}
else {output = 1440 - (startInMinutes - endInMinutes)}
return output
}
i have some clock script. Everything is fine and it's work perfectly but... i have one problem. If at the clock is set one digit hour or minute like 1:5 clock not adding "0" digit before. This what i'v done but it does't work. Can u help me, much thx?
window.setInterval(function update_clock() {
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
$.ajax({
success: function (clock) {
document.getElementById("hour").firstChild.nodeValue = currentHours;
document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
if (currentMinutes.length == 1) {
currentMinutes = "0" + currentMinutes;
}
}
});
}, 999);
You may use .slice to extract a portion of a string. Pass a negative number to it, in order to slice from the end of the string.
Therefore, the following is possible, and quite simple:
('0'+currentMinutes).slice(-2)
Concatenating with '0' makes sure that the target of the operation will always be a string. ('0'+currentMinutes) will yield a 2 or 3 letter string ("07" or "017", for instance). Slicing the last two characters off that string will give you a 0-padded two-digit number.
Note that the above would yield "00" if currentMinutes is 100, so it assumes that you know the values you'll be working with.
This could be extracted to something more reusable:
Number.prototype.zeroPad = function() {
return ('0'+this).slice(-2);
};
That would allow you to write:
currentMinutes.zeroPad();
You could also make the length of the padding variable:
Number.prototype.zeroPad = function(length) {
length = length || 2; // defaults to 2 if no parameter is passed
return (new Array(length).join('0')+this).slice(length*-1);
};
Which could be called as:
currentMinutes.zeroPad(); // e.g. "07" or "17"
currentMinutes.zeroPad(3); // e.g. "007" or "017"
Note that while currentMinutes.zeroPad() will work, 7.zeroPad() would not.
currentMinutes is a number, so it does not have the length property. Also, you must check the length before set the currentMinutes to the minutes element.
Something like:
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
$.ajax({
success: function (clock) {
if (currentMinutes.toString().length == 1) {
currentMinutes = "0" + currentMinutes;
}
document.getElementById("hour").firstChild.nodeValue = currentHours;
document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
}
});
Try using the padStart() method. Based on MDN docs, the padStart() method keeps padding the string with another string until it reaches the desired length. Link to MDN docs on padStart().
If you want to format your string to have 4 digits with leading zeros if less than 4 digits are available. The padStart() method can come to the rescue as follows:
let str = "34"
str = str.padStart(4, "0") // results in "0034"
console.log(str)
An example of the date case:
var now = new Date();
var year= now.getFullYear();
var month= (now.getMonth()+1).toString().padStart(2, "0");
var day= now.getDate().toString().padStart(2, "0");
var hour = now.getHours().toString().padStart(2, "0");
var minute = now.getMinutes().toString().padStart(2, "0");
document.getElementById("date").innerHTML =`${day}-${month}-${year}-${hour}:${minute}`;
<div id="date"></div>
currentMinutes won't have a length property, as it's a Number, not a String.
You could force it to be a String.
if ((currentMinutes+'').length == 1) {
currentMinutes = "0" + currentMinutes;
}
But, because you have a Number, you should make your condition...
if (currentMinutes < 10) {
currentMinutes = "0" + currentMinutes;
}
If you were especially crazy, you could do...
var hoursMinutes = ((new Date)+"").match(/\d+:\d+(?=:)/)[0].split(":");
You could also check sprintf() for javascript.
You could go with something as simple as:
sprintf("%02d:%02d", currentHours, currentMinutes);
Using functions that accept formatting lets you have much more control over your output, when you need to.
in android(build in)
String time=String.format("%02d:%02d",hourOfDay,minute);
in javascript use (sprintf.js)
int i = 1;
string s = sprintf("%02d", i);
document.write(s); // Prints "01"
sprintf.js:
http://www.diveintojavascript.com/projects/javascript-sprintf
Based on the other awnsers, I created this lines of code:
var now = new Date();
var dd = now.getDate();
var mm = now.getMonth()+1;
var y = now.getFullYear();
var h = now.getHours();
var m = now.getMinutes();
function aZero(n) {
return n.toString().length == 1 ? n = '0' + n: n;
}
document.getElementById("out").innerHTML =
aZero(dd) + "-" +
aZero(mm) + "-" +
y + " - " +
aZero(h) + ":" +
aZero(m);
<div id="out">my time :D</div>
Cu next time.
Try use ('0' + currentTime.getHours()).slice(-2)
Updated your Question -
window.setInterval(function update_clock() {
var currentTime = new Date();
var currentHours = ('0' + currentTime.getHours()).slice(-2);
var currentMinutes = ('0' + currentTime.getMinutes()).slice(-2);
$.ajax({
success: function (clock) {
document.getElementById("hour").firstChild.nodeValue = currentHours;
document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
if (currentMinutes.length == 1) {
currentMinutes = "0" + currentMinutes;
}
}
});
}, 999);
You could do based on length.
My solution will be
var mnt = '' + (seconds / 60).toFixed();
if (mnt.toString().length == 1) mnt = '0' + mnt;
var sec = '' + (seconds % 60).toFixed();
if (sec.toString().length == 1) sec = '0' + sec;
return `${mnt}:${sec}`;
ok so im trying to create something where certain elements change based on time of day. that time of day is gotten via system clock.
heres my code:
var currTime = new Date();
var currHrs = currTime.getHours();
var currMins = currTime.getMinutes();
var currSecs = currTime.getSeconds();
if (currMins < 10){
currMins = "0" + currMins;
}
var suffix = "AM";
if (currHrs >= 12) {
suffix = "PM";
currHrs = currHrs - 12;
}
if (currHrs == 0) {
currHrs = 12;
}
//display thr and minutes .
var myTime = currHrs + ":" + currMins;
if(myTime< 12){
document.getElementById("clock").innerHTML = myTime;
} else {
//code here
}
problem im having is that the time isnt being written at all in the html "clock" div.
i know it works because if i take out the 'if' and just do the document.write etc, its prints to screen.
im assuming that the problem is the myTime > 12 part. if i do '>' or '<' , it still doesnt work.
what i want is that say for example, if its before 12pm something happens, etc. i just dont know how to target for example, morning time from noon, night etc.
any ideas, etc ill gladly appreciate.
thanks in advanced.
Yes, your problem is your if condition, or perhaps what comes before it.
//display thr and minutes .
var myTime = currHrs + ":" + currMins;
You have created myTime as a string e.g. "12:30". Obviously this is not suitable for comparison with a number.
It won't work with currHrs either because, with your logic, that is never a number less than 12.
I suggest you map out in pseudo code what it is you are trying to accomplish, as it all seems a bit muddled up there.
You were close. I simply moved a few things around for you.
Edited: Made a few mistakes in my haste. And apologies for syntax error. Fixed now.
var currTime = new Date();
var currHrs = currTime.getHours();
var currMins = currTime.getMinutes();
var currSecs = currTime.getSeconds();
if (currMins < 10) {
currMins = "0" + currMins;
}
var suffix = "AM";
if (currHrs >= 12) {
suffix = "PM";
currHrs = currHrs - 12;
} else if (currHrs == 0) {
currHrs = 12;
}
var myTime = (currHrs == 0 ? 12 : currHrs) + ":" + currMins + " " + suffix;
if (myTime.match(/(AM)/)) {
document.getElementById("clock").innerHTML = myTime;
} else {
// code here
}
After this line myTime is a string
var myTime = currHrs + ":" + currMins;
You're doing a string comparison to an int below.
if(myTime< 12){
document.getElementById("clock").innerHTML = myTime;
} else {
//code here
}
Did you mean to do this ?
if(currHrs < 12){
document.getElementById("clock").innerHTML = myTime;
} else {
//code here
}
I m trying to calculate a day diff in Javascript to apply some value. The first expression
if subs_start
is working fine, but the second one
subs_end
is not working, same goes with
subs_mid
Code:
var subs_start = 0;
var subs_mid = 0;
var subs_end = 0;
var dayDiff = (end_year*365 + end_mon * 30 + end_day)
- (start_year*365 + start_mon* 30 + start_day);
var oneDay=1000*60*60*24;
var oneHour = 1000*60*60;
var timeDiff = endDate.getTime() - startDate.getTime();
var hourDiff = timeDiff/oneHour;
var start_rem_hour = 24 - start_hour*1;
$.each(subsistence, function(id,subs){
if(subs.start <= start_rem_hour && start_rem_hour < subs.end ){
subs_start = subs.rate;
}
alert('T' + end_hour);
if(subs.start <= end_hour && end_hour < subs.end ){
subs_end = subs.rate;
alert ('e ' + subs_end);
}
if(dayDiff > 2){
if(subs.start >= 10){
subs_mid = subs.rate * (dayDiff - 2);
alert ('m ' + subs_mid);
}
}
});
var subs_allow = subs_start*1 + subs_mid*1 + subs_end*1 ;
I m finally able to find the answer. I need to multiple start_rem_hour and end_hour with 1 to convert into int. It seems js is taking them as string and when i multiply with 1 it gets into integer scope.
Not sure what is being asked for.
For DateTime calculations in javascript I would recommend Datejs library:
http://www.datejs.com/