Checking if time, from string, is greater then current time - javascript

I have some string like
ex. '8:00 AM' '12:00 PM' '2:00 PM'
how can I check in javascript or jquery to see if this time is past the current time?
Here is what I've tried so far but the isAfter method doesn't seem to work
var time = moment(startTime, 'HH:mm A'); //.format('HH:mm A');
if (time.isAfter(moment())) {
yb.base.eventAlert("You can't create events in the past! Try refreshing your page", "info");
return false;
}
UPDATE - I figured it out!
I had to use 'hour minute' as a condition
if (moment().isAfter(time, 'hour minute')) {
yb.base.eventAlert("You can't create events in the past! Try refreshing your page", "info");
return false;
}

Try this function :
function checktime() {
var dt = new Date(); //Get current time
var time = dt.getHours() + ":" + dt.getMinutes(); //Get hour and minutes
var timeStr = document.getElementById('time').value; // Get string time
var parts = timeStr.split(':'); // Split string to get hours and minutes
var hour = parseInt($.trim(parts[0]));
// swap am & pm
if (parts[1].match(/(AM|am)/)) {
if (hour == 12) {
// easily flip it by adding 12
hour = 0;
}
parts[1] = parseInt(parts[1])
} else {
if (hour < 0) {
hour = hour + 12
}
parts[1] = parseInt(parts[1]);
}
timeStr = hour + ':' + parts[1];
if (hour > dt.getHours() && parts[1] > dt.getMinutes) {
console.log("Past time");
console.log(hour + " " + dt.getHours());
} else if (hour == dt.getHours() && parts[1] > dt.getMinutes) {
console.log("Past time");
console.log(hour + " " + dt.getHours());
} else {
console.log("Not Past time");
console.log(hour + " " + dt.getHours());
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="time" placeholder="Insert time" />
<button onclick="checktime();">Check time</button>

This solved it
if (moment().isAfter(time, 'hour minute')) {
yb.base.eventAlert("You can't create events in the past! Try refreshing your page", "info");
return false;
}

function isPastCurrentTime (time){
let timeNow = new Date();
//converts timeNow to just the date string
let date = timeNow.toLocaleDateString();
//adds the time to check to the date string, converts it to milliseconds
//then truncates the last four digits to compare minutes
//instead of milliseconds
let timeToCheck = Math.floor(new Date(date + ' ' + time).getTime() / 60000);
//converts timeNow to milliseconds, then truncates the last four digits
//to compare minutes instead of milliseconds
let currentTime = Math.floor(timeNow.getTime() / 60000);
return timeToCheck > currentTime;
}

Related

Jquery function to Increment one hours based on time input string

I have string value in this format.
9:00 am
i want it to be like this.
9:00 am - 10:00 am
second hour must be 1 greater then first one. for example if time is
7:00 am then it should be 7:00 am - 8:00 am
how can i do that using jquery?
i tried this but its not working as it works now.
var time= "9:00 am"
var nexttime=time.setHours(time.getHours()+1)
alert(nexttime);
getting error of
time.getHours is not a function
You can try this :
function increaseTimeByOne(timeStr) {
var splitedTimeStr = timeStr.split(':');
var hours = parseInt(splitedTimeStr[0]);
var meridiem = splitedTimeStr[1].split(" ")[1];
var minutes = splitedTimeStr[1].split(" ")[0];
var nextHours = (hours + 1);
var nextMeridiem;
if (hours >= 11) {
if (meridiem.toLowerCase() == "am") {
nextMeridiem = "pm";
} else if (meridiem.toLowerCase() == "pm") {
nextMeridiem = "am";
}
if (nextHours > 12) {
nextHours = nextHours - 12;
}
} else {
nextMeridiem = meridiem;
}
return nextHours + ":" + minutes + " " + nextMeridiem;
}
and using above function as
var timestr="9:00 am";
var next_hour = increaseTimeByOne(timeStr);
alert(next_hour);
refer this
var time=new Date();
time.setHours(9, 00, 00);
var nexttime=(time.getHours()+1);
alert(nexttime);
// to get hrs mins and seconds
var nexttime=(time.getHours()+1) +":"+time.getMinutes()+":"+time.getSeconds();
YOu can make your time string like:
function increaseTimeByOne(t) {
var s = t.split(':');
var n = parseInt(s[0], 10);
var nt = (n + 1) + ":00 ";
var ampm = n >= 11 ? "pm" : "am";
return t + " - " + nt + ampm;
}
console.log(increaseTimeByOne('9:00 am'));
console.log(increaseTimeByOne('11:00 am'));
console.log(increaseTimeByOne('12:00 pm'));

Page last modified using Javascript with 12 hour clock showing am or pm

I'm trying to create a script in Javascript that shows when a page was last modified, which returns the date, time, in am or pm format, of modification.
Clearly I am doing something wrong. I can't get the script to run, and it will be in my function AmPm. Can someone please help?
// Javascript code for page modification
// Shows the date, time, am or pm, of modification.
// This section sets the date of modification
function lastModified() {
var modiDate = new Date(document.lastModified);
var showAs = modiDate.getDate() + "." + (modiDate.getMonth() + 1) + "." + modiDate.getFullYear();
return showAs
}
// This section sets the time of modification
function GetTime() {
var modiDate = new Date();
var Seconds
if (modiDate.getSeconds() < 10) {
Seconds = "0" + modiDate.getSeconds();
} else {
Seconds = modiDate.getSeconds();
}
// This section writes the above in the document
var modiDate = new Date();
var CurTime = modiDate.getHours() + ":" + modiDate.getMinutes() + ":" + Seconds
return CurTime
}
// This section decides if its am or pm
function AmPm() {
var hours = new Date().getHours();
var hours = (hours + 24 - 2) % 24;
var mid = 'AM';
if (hours == 0) { // At 00 hours (midnight) we need to display 12 am
hours = 12;
} else if (hours > 12) // At 12pm (Midday) we need to display 12 pm
{
hours = hours % 12;
mid = 'PM';
}
}
var mid = //This is where I am stuck!!
return AmPm
document.write("This webpage was last edited on: ");
document.write(lastModified() + " at " + GetTime() + AmPm());
document.write("");
document.write(" NZ Daylight Savings Time.");
document.write("");
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}

Convert timestamp from am/pm to 24-hour in Javascript

I'm using jquery timepicker. On user side, time needs to be displayed as am/pm format (10:30am or 5:30pm). I need to append that value to datepicker value.
For example, if datepicker value is 07/08/2015, final value should be 07/08/2015 17:30.
Problem here is in converting 5:30pm to 17:30. How to do it with javascript
You could write your own conversion function that converts time-strings with "pm" in them by adding 12 hours, like so:
var convertTimeStringTo24Hours = function(timeString) {
if (timeString.match(/pm$/)) {
var match = timeString.match(/([0-9]+):([0-9]+)pm/);
var hours = parseInt(match[1]) + 12;
var minutes = match[2];
return hours + ':' + minutes;
} else {
return timeString.replace('am', '');
}
};
In case you want to convert from the 12 Hour system(hh:mm:ssPM/AM) to 24 Hour system then you could use the following
function timeConversion(s) {
const timeString = s.toString()
if (timeString.match(/PM$/)) {
var match = timeString.match(/([0-9]+):([0-9]+):([0-9]+)PM/)
var hours = parseInt(match[1]) + 12;
var minutes = match[2];
var second = match[3]; parseInt(match[1])
if (parseInt(match[1]) === 12) {
return parseInt(match[1])+ ':' + minutes + ':' + second;
} else {
return hours + ':' + minutes + ':' + second;
}
} else {
var match = timeString.match(/([0-9]+):([0-9]+):([0-9]+)AM/)
var hours = parseInt(match[1]);
var minutes = match[2];
var second = match[3];
if (hours === 12) {
return '00:' + minutes + ':' + second;
} else {
return timeString.replace('AM', '');
}
}
}

Compare hardcoded date with the current date

I am trying to compare dates in javascript.
I have a hardcoded date (03/23/2015 11:20 am) in of , and I am trying to compare it with the current date in the same format.
But I am always getting it as not same.
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var timeNow = formatDate(D);
var startTime6 = document.getElementById('tno6_time').innerHTML;
if (timenow == startTime6) {
alert("Same");
}
else {
alert("not same");
}
Your's javascript portion :
var d = new Date();
var timeNow = formatDate(D);
if (timenow == startTime6) {
alert("Same");
}
Here check in above code you are creating variable with name d and you are passing variable D which is not declared.Here you have also typo in timeNow not timenow.It should be like
var timeNow = formatDate(d);
if (timeNow == startTime6) {
alert("Same");
}
Apart from that check both the variables value either with console.log() function or with alert() and see if there are same then It should alert the 'Same' else 'not same'.
And keep in mind new Date() will always give you current time so if you are comparing with hard coded date then Only once there are the possibility that result should come 'Same' and It will only occur when you are executing this code when the hard coded date and time exactly the same.
It is very hard to check your code in that way because millisecond change will affect your result.
Check this demo

How to check if current time falls within a specific range considering also minutes

I am doing a Website for Restaurants Home Delivery ,depending on Restaurant's Home Delivery Timings i need to enable / disable Order Now Button
I have got startTime and End Time in 12 Hour format .
This is the code
var startTime = '8:30 AM' ;
var endTime = '6:30 PM' ;
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"),hours24>11?"pm" :"am"].join(" ");
}
return formatted;
}
})();
var currentTime = formatTime(new Date());
I need to check if the current time is in between startTime and EndTime or not
If its only Hours ,i could have extracted the first character before colon from startTime ,endTime and currentTime and done a comparision like this
if(currentTime >= startTime && currentTime <= endTime)
{
alert('Restaurant Open');
}
else
{
alert('Restaurant Closed');
}
But i need to take the minutes also in consideration ,so could you please let me how to do this comparsion if minutes were takein in consideration ??
How to check if current time falls within a specific range considering also minutes
Something like this should work
var startTime = '6:30 PM';
var endTime = '8:30 AM';
var now = new Date();
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
if (startDate > endDate) { // check if start comes before end
var temp = startDate; // if so, assume it's across midnight
startDate = endDate; // and swap the dates
endDate = temp;
}
var open = now < endDate && now > startDate ? 'open' : 'closed'; // compare
console.log('Restaurant is ' + open);
function dateObj(d) { // date parser ...
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date;
}
.as-console-wrapper {top : 0!important}
It splits those times and adds 12 to PM times, then creates date objects that can easily be compared.
Doesn't seem to work with times passing midnight, try changing the time from 6:30PM to 2:30AM. A good solution is to use momentjs with the moment-range plugin
function inTimeRange(time, startTime, endTime)
{
//Setup today vars
var today = new moment(new Date());
var ayear = today.year();
var amonth = today.month() + 1; // 0 to 11
var adate = today.date();
amonth = String(amonth).length < 2 ? "0" + amonth : amonth;
adate = String(adate).length < 2 ? "0" + adate : adate;
//Create moment objects
var moment1, moment2;
var temp = endTime.split(" ");
if(temp[1].toLowerCase() == "am")
{
var test1 = ayear + "-" + amonth + "-" + adate + " " + startTime;
var test2 = ayear + "-" + amonth + "-" + adate + " " + endTime;
//Make sure that both times aren't morning times
if(moment(test2).isAfter(test1))
{
var moment1String = ayear + "-" + amonth + "-" + adate + " " + startTime;
var moment2String = ayear + "-" + amonth + "-" + adate + " " + endTime;
}
else
{
var moment1String = ayear + "-" + amonth + "-" + adate + " " + startTime;
var moment2String = ayear + "-" + amonth + "-" + (adate + 1) + " " + endTime;
}
moment1 = moment(moment1String, "YYYY-MM-DD HH:mm A");
moment2 = moment(moment2String, "YYYY-MM-DD HH:mm A");
}
else
{
var moment1String = ayear + "-" + amonth + "-" + adate + " " + startTime;
var moment2String = ayear + "-" + amonth + "-" + adate + " " + endTime;
moment1 = moment(moment1String, "YYYY-MM-DD HH:mm A");
moment2 = moment(moment2String, "YYYY-MM-DD HH:mm A");
}
//Run check
var start = moment1.toDate();
var end = moment2.toDate();
var when;
if(String(time).toLowerCase() == "now")
{
when = moment(new Date());
}
else
{
var timeMoment1String = ayear + "-" + amonth + "-" + adate + " " + time;
when = moment(timeMoment1String);
}
var range = moment().range(start, end);
return when.within(range);
}
var startTime = '02:30 AM';
var endTime = '13:00 PM';
var now = new Date();
var startDate = dateObj(startTime);
var endDate = dateObj(endTime);
alert(endDate)
var open = now < endDate && now > startDate ? 'open' : 'closed';
alert('Restaurant is ' + open);
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date;
}
var startTime = '8:30 AM';
var endTime = '6:30 PM';
var now = new Date();
var startDate = dateObj(startTime);
var endDate = dateObj(endTime);
var open = now < endDate && now > startDate ? 'open' : 'closed';
alert('Restaurant is ' + open);
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date;
}
I have done something similar to this. My app was receiving times in military time. So in the case where times didn't pass into the next day (i.e. start time of 09:00 and end time of 17:00 you would just check if you are between those times.
In the case of the end time being after midnight (i.e. start time of 15:00 and end time of 01:00) then there are three cases:
You are in a time after both start and end times, like 16:00, in which case you are inside business hours
You are in a time before both start and end times, like 00:30, in which case you are also inside business hours.
You are in a time after the end time, but before the start time, like 02:30, in which case you are outside of business hours
Here is my code sample:
const isCurrentDayPart = (dayPart) => {
let currentTime = moment();
let startTime = moment(dayPart.startTime, "HH:mm");
let endTime = moment(dayPart.endTime, "HH:mm");
if (dayPart.startTime < dayPart.endTime) {
return currentTime.isBetween(startTime, endTime);
} else {
if (currentTime.isAfter(endTime) && currentTime.isAfter(startTime)) {
return true;
} else if (currentTime.isBefore(endTime) && currentTime.isBefore(startTime)) {
return true;
}
}
return false;
};

Categories

Resources