Check if time is falling under specific timeframe - javascript

I have a variable that stores a time value.
var cabtime = ["09:30:00"];
Variable time value is in 24-hour clock. That means 02:30:0PM will come as 14:30:00.
I want to check if the variable time falls under 08:00AM to 10:00AM window. If yes then I'll do an action.
Any pointers in this regard?

You could parse the time into seconds since midnight using:
var cabtime = ["HH:MM:SS"] // in 24hr time
function parseTime (string) {
parts = string.split(':').map(x => parseInt(x))
seconds = parts[0] * 3600 + parts[1] * 60 + parts[0]
return seconds
}
Then you can parse the time and the upper/lower bounds, and test using:
time = parseTime(cabtime[0])
lower = parseTime('08:00:00')
upper = parseTime('10:00:00')
if (time >= lower && time <= upper) {
print('Inside the range')
}

You can solve it easily by converting your strings to Date objects and compare them than.
var cabtime = ["09:30"];
function checkTimeRange(time, from, to, reldate) {
if (undefined === reldate) {
reldate = '0000T'; // the date the time strings are related to
}
let dtime = new Date(reldate + time);
let dfrom = new Date(reldate + from);
let dto = new Date(reldate + to);
return dfrom <= dtime && dtime <= dto;
}
checkTimeRange(cabtime[0], '08:00', '10:00'); // returns true
If you have full dates (e.g. '2019-07-25T09:30:00') instead of just the clock time you should provide for the parameter `reldate' an empty string.
* update: changed the wrong date format to standard format
* update: changed the date format again to be more fancy

Related

How to check if value is 10 or more minutes from now?

I'd like to check if value is 10 or more mins from now.
let now = new Date().getTime();
let TEN_MINUTES = new Date().getTime() + 600000;
let val = '2022-01-14 12:27:05+00:00'
if(val > TEN_MINUTES){
console.log('true')
}
val is a non-blank string, so val > tenMinsPlus doesn't make any sense, since tenMinsPlus is a boolean.
If you want to know whether val is more than ten minutes from now, you need to get a date-like value for val and a date-like value for ten minutes from now, and compare them.
You're getting TEN_MINUTES correctly:
let TEN_MINUTES = new Date().getTime() + 600000;
although you can do that more concisely:
let TEN_MINUTES = Date.now() + 600000;
Both of those give us a number of milliseconds since The Epoch (Jan 1st 1970 at midnight UTC) for "now" plus ten minutes.
Now let's do the date. Your string is almost in a valid format for the Date object to parse. It just needs the space after the date changed into a T, then we can use Date.parse to parse it and give us the number of milliseconds since The Epoch:
let then = Date.parse(val.replace(" ", "T"));
Then we see whether then is greater than TEN_MINUTES:
if (then > TEN_MINUTES) {
// Yes, it's more than ten minutes from now
} else {
// No, it isn't
}
Live Example:
function moreThan10Minutes(val) {
let TEN_MINUTES = Date.now() + 600000;
let then = Date.parse(val.replace(" ", "T"));
return then > TEN_MINUTES;
}
function test(val) {
const result = moreThan10Minutes(val);
if (result) {
console.log(`Yes, ${val} is more than 10 minutes from now`);
} else {
console.log(`No, ${val} is not more than 10 minutes from now`);
}
}
test("2022-01-14 12:27:05+00:00");
test(new Date(Date.now() + 700000).toISOString());

Increase time by an hour before comparing

I have code containing time in the military format.
<div class="em" data-time="17:30">
I am comparing that time to the current time to determine if the set time has passed or not.
var curDate = new Date(),
curTime = curDate.getTime(),
givenTm = $(this).find('.em').attr('data-time'),
givenMs = Date.parse(curDate.toDateString() + ' ' + givenTm);
if (curTime > givenMs) {
// time has passed
}
I need to modify my code to check not against the time in data attribute, but an hour after that given time. Also my given time can only be on the same day and no later then 23:30, which means I only care if the given time is no later then 23:00.
How do I put all this together?
To adjust by an hour, just add one hour in milliseconds (60 * 60 * 1000) to the comparison. To ignore any given time after 2300, you'll need to add another clause into the conditional. So something like this might do it:
if (new Date(givenMs).getHours() < 23
&& curTime > givenMs + 3600000) {
// time has passed
}
Hopefully that helps.
Try using .toJSON , String.prototype.replace() , String.prototype.slice()
$("div").click(function() {
var curDate = new Date(),
curTime = curDate.toJSON(),
givenTm = $(this).find(".em").attr("data-time")
.replace(/(\d+)(?=:)/, function(match) {
return Number(match) + 1
}),
curr = curTime.slice(11, -8).replace(":", ""),
given = givenTm.replace(":", "");
if (curr < 2330 && given < 2330) {
// time has passed
console.log("currTime:", curr, "givenTime:", given,
"time has not passed")
} else {
console.log("time has passed")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>click
<div class="em" data-time="17:30">
</div>

Javascript date parsing YYYY-MM-DD HH:MM:SS T [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 8 years ago.
I need to parse a string to date which comes in below format
2012-05-23 12:12:00-05:00
Date.parse("2012-05-23 12:12:00-05:00")
It is working fine with chorme but not in Firefox and IE. Any suggestions would be helpful.
I deleted my previous (less relevant) answer. This function should suit your purposes much better.
The key strategy is to get an absolute representation of your time without the time zone, and then adjust it backward or forward based on the specified timezone. What it spits out is a Date object in your browser's local time zone, but it will represent exactly the same moment in time as the string does.
Also, the format you specified isn't quite to spec, so the regex I wrote accepts your version as well as ISO8601.
Date.createFromString = function (string) {
'use strict';
var pattern = /^(\d\d\d\d)-(\d\d)-(\d\d)[ T](\d\d):(\d\d):(\d\d)([+-Z])(\d\d):(\d\d)$/;
var matches = pattern.exec(string);
if (!matches) {
throw new Error("Invalid string: " + string);
}
var year = matches[1];
var month = matches[2] - 1; // month counts from zero
var day = matches[3];
var hour = matches[4];
var minute = matches[5];
var second = matches[6];
var zoneType = matches[7];
var zoneHour = matches[8] || 0;
var zoneMinute = matches[9] || 0;
// Date.UTC() returns milliseconds since the unix epoch.
var absoluteMs = Date.UTC(year, month, day, hour, minute, second);
var ms;
if (zoneType === 'Z') {
// UTC time requested. No adjustment necessary.
ms = absoluteMs;
} else if (zoneType === '+') {
// Adjust UTC time by timezone offset
ms = absoluteMs - (zoneHour * 60 * 60 * 1000) - (zoneMinute * 60 * 1000);
} else if (zoneType === '-') {
// Adjust UTC time by timezone offset
ms = absoluteMs + (zoneHour * 60 * 60 * 1000) + (zoneMinute * 60 * 1000);
}
return new Date(ms);
};
Use moment.js's date parsing:
var date = moment("2012-05-23 12:12:00-05:00");
See http://momentjs.com/docs/#/parsing/string/

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

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.

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.

Categories

Resources