Javascript regext time format detection - javascript

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;
}
}

Related

How to calculate duration between two times in Google scripts for spreadsheet [duplicate]

This question already exists:
Google scripts subtracting times
Closed 7 years ago.
I would like to create a custom function that calculates the duration between two or more hours. The result can be positive or negative.
Other people can benefit using the function in any given coordinates not limiting to a specific range.
Example input:
Inputs: Output:
A B C D
-26:55 06:38 22:39 -04:16
02:19 00:00 04:33 02:19
I've tried without success many alternatives:
function saldo(A,B,C) { // best desired...
if(A == 0) {
return (-B)+C ;
}
else if (A<0 && (-A)<C && (-A)-C<B){
return (A)+C-B;
}
else if (A<0 && (-A)>C){
return (-B);
}
function xis(A,B) {
// var addedDate = sheet.getRange(1,1).getValue();
// var a1 = Utilities.formatDate(A, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "HH:mm");
// var b1 = Utilities.formatDate(B, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "HH:mm");
var a1 = new Date.getHours(A) + date.getMinutes(A);
var b1 = new Date.getHours(B) + date.getMinutes(B);
if (a1 > b1){
return B;
}
else {
return A;
}
}
function tentativa(a,b){
var t1 = a.getTime();
var t2 = b.getTime();
var outnumber = t1 - t2;
return Utilities.formatDate(new Date(outnumber), "GMT-3", "hh:mm");
}
function worked(time1,time2)
{
//var time1;
//var time2;
var outnumber = time1 - time2;
// return msToTime(outnumber)
return msToTime(outnumber);
// return Utilities.formatDate(new Date(outnumber), "GMT", "HH:mm");
}
function msToTime(duration) {
var milliseconds = parseInt((duration%1000)/100)
, seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(1000*60*60))%24);
// hours = hours : hours;
// minutes = minutes : minutes;
// seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
You should only need 2 inputs to find the difference between two hour variables.
I have a small javascript code snippet which takes 2 inputs in hh:mm format and outputs the difference. You could extrapolate this logic for hh:mm:ss formats. You can call the function repeatedly to solve for 3 or more inputs.
// Code snippet to calculate the difference between 2 inputs of time in hh:mm 24hrs format
// Author: Harish Narayanan
// Date: 04-May-2015
function getHourDiff(a, b) {
if (!isValidHour(a) || !isValidHour(b)) {
return "Invalid input(s)";
}
var h1 = a.split(":"), h2 = b.split(":");
var h = 0, m = 0;
h = h1[0] - h2[0];
m = h1[1] - h2[1];
if (h < 0) {
h = -h;
m = -m;
}
if (h == 0) {
m = Math.abs(m);
}
if (m < 0) {
m = m + 60;
h = h - 1;
}
return h+":"+m;
}
function isValidHour(hour) {
hourPattern = "^([01]?[0-9]|2[0-3]):[0-5][0-9]$";
if (hour.match(hourPattern)) {return true;}
return false;
}

How to work out time difference between two times on a 24 hour clock

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
}

Javascript Countdown with PHP

I want to have a countdown associated with a particular button on my PHP page and i am using following code based on javascript
But,it resets the target value on page reload,so how to have the same without the target value getting reset.Can i do something with session ??
<html>
<body>
<p>Time remaining: <span id="countdownTimer"><span>00:00.<small>00</small></span></p>
<script type="text/javascript">
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown() {
var now = new Date();
if ( (now.getDay() >= 0) && (now.getDay() <= 6) ) { // Monday to Friday only
var target = 23; // 15:00hrs is the cut-off point
if (now.getHours() < target) { // don't do anything if we're past the cut-off point
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}
}
}
var timerRunning = setInterval('countDown()', 1000);
}
</script>
</body>
</html>
Instead of evaluating your variable 'now' as such:
var now = new Date();
Evaluate it like this (assuming our browser supports LocalStorage):
if (!localStorage.myDate)
localStorage.myDate = (new Date()).toString();
var now = new Date(localStorage.myDate);
This way, we only ever evaluate the current date on first load. After that, we refer to a serialized string version of that date and pass that as an argument when we create our 'now' variable.
If we want to support older browser (cough IE), we can use userData or simply do something very similar with cookies.
So essentially, you want to capture 'now' once, and not have that change, correct?
function getNow(){ //call this rather than use var now = new Date();
if (window.localStorage){
if (!localStorage.now){
localStorage.now = new Date();
}
return localStorage.now;
}else{
return new Date();
}
}
Pardon if I've got a bit of syntax out (I'm not sure if you'd have to convert a date to store it in localStorage), but that's the gist of it. For IE7 and below support you'd need to use cookies, but the concept remains the same.
Also, I think you have a mistake in:
if ( (now.getDay() >= 0) && (now.getDay() <= 6) )
That will always be true, try:
if ( (now.getDay() > 0) && (now.getDay() < 6) )

convert time string format

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";
}

.js help with the Date object and if/else

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
}

Categories

Resources