I want it to be in loop. any idea? or is it not possible? should i do loop in php instead? the idea is to check if today or tomorrow date are listed inside the date that is not available to be selected.
//array
var disabledArr = ["09/29/2019","09/30/2019"];
//for loop
var j = disabledArr.length;
//convert date
function formatDate(date) {
var d = new Date(date),enter code here
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [month, day, year].join('/');
}
var today = new Date();
var today1 = formatDate(today);
var n = disabledArr.includes(today1);
if(n == true){
today.setDate(today.getDate() + 1);
}
var today2 = formatDate(today);
var n = disabledArr.includes(today2);
if(n == true){
today.setDate(today.getDate() + 1);
}
var today3 = formatDate(today);
var n = disabledArr.includes(today3);
if(n == true){
today.setDate(today.getDate() + 1);
}
var today4 = formatDate(today);
Related
I have a date in datetime and I need to calculate it with the current date in javascript to check if 7 days have passed.
var created_at = 2021-05-20; //return 2021-05-20 14:00:00
var data = new Date();
var dataAtual = data.getFullYear() + "-" + ("0" + (data.getMonth() + 1)).substr(-2) + "-" + ("0" + data.getDate()).substr(-2);
var result = data - created_at;
if(result < 7){
var create_date = true;
console.log(true);
} else {
var created_date = false;
console.log(false);
}
Can you try the below code
var date1 = new Date('2021-05-20 14:00:00')
var date2 = new Date()
var resulu = date2.getDate() - date1.getDate()
if(result < 7){
var create_date = true;
console.log(true);
} else {
var created_date = false;
console.log(false);
}
Get the difference of dates in milliseconds and convert into days.
const old_date = new Date('2021-05-20');
const today = new Date();
const diff_days = (today - old_date) / 24 * 60 * 60 * 1000;
if (diff_days < 7) {
console.log('older than a week');
} else {
console.log('in last week');
}
Do not know what i'm doing wrong and would like some help to fix it i am trying to make script to write out the day date and time like this It is currently: 3:15 PM on Wednesday, September 21. this is what i have
function renderTime(){
var mydate = new date();
var year = mydate.getYear();
if(year < 1000){
year +=1900
}
var day = mydate.getDay();
var month = mydate.getMonth();
var daym = mydate.getDate();
var dayarray = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var montharray = new Array("Jannuary","Februry","March","April","May","June","July","Augest","September","October","November","December");
var currentTime = new Date();
var h = currentTime.getHour();
var m = currentTime.getMinutes();
var ampm = h >= 12 ? 'pm' : 'am';
if(h == 24){
h = 0;
} else if (h > 12 ){
h = h - 0;
}
if(h < 10){
h = "0" + h;
}
if(m < 10){
m = "0" + m;
}
}
document.write("It is currently"+h+m+"on"+dayarray[day]+ montharray[month]+daym);
You can simplify it by using toLocaleDateString and toLocaleTimeString:
var myDate = (new Date()).toLocaleDateString("en-US", {weekday: 'long',month: 'long',day: 'numeric'});
var myTime = (new Date()).toLocaleTimeString("en-US", {hour: 'numeric',minute: 'numeric'
});
var message = 'It is currently: ' + myTime + ' on ' + myDate;
console.log(message);
var mydate = new Date();
var year = mydate.getYear();
if(year < 1000){
year +=1900
}
var day = mydate.getDay();
var month = mydate.getMonth();
var daym = mydate.getDate();
var dayarray = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var montharray = new Array("Jannuary","Februry","March","April","May","June","July","Augest","September","October","November","December");
var currentTime = new Date();
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var ampm = h >= 12 ? 'pm' : 'am';
if(h == 24){
h = 0;
} else if (h > 12 ){
h = h - 12;
}
if(h < 10){
h = "0" + h;
}
if(m < 10){
m = "0" + m;
}
document.write("It is currently "+h+ ":"+ m+ ampm +" on "+dayarray[day] + ' ' + montharray[month] + ' '+daym);
let dateString = new Date().toLocaleDateString("en-US").split("/");
// returns an array ["month", "day as number in month", "year"]
let timeString = new Date().toLocaleTimeString("en-US").split(/:| /);
// returns an array ["hour", "minute", "second", "am or pm"]
let weekDayNumber = new Date().getDay();
let days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
let months = ["Jannuary","Februry","March","April","May","June","July","Augest","September","October","November","December"];
document.write("It is currently"+timeString[0]+timeString[1]+"on"+days[weekDayNumber ]+ months[dateString[0]]+dateString[1]);
You're running all your date rendering in a function which keeps all your interim variables private. This is a good thing, but you're not providing any way to get the result out. Include a return statement in your function to return the formatted string like this:
return ("It is currently "+h+":"+m+" on "+dayarray[day]+" "+ montharray[month]+" "+daym);
You create a new Date object for time, but you should just use the one you created for date, and you missed a letter of a method name. Here's the revised version:
function renderTime(){
var mydate = new Date();
var year = mydate.getYear();
if(year < 1000){
year +=1900
}
var day = mydate.getDay();
var month = mydate.getMonth();
var daym = mydate.getDate();
var dayarray = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
var montharray = new Array("January","Februry","March","April","May","June","July","Augest","September","October","November","December");
// re-use mydate here instead of creating a new object.
var h = mydate.getHours(); // You missed the 's' off 'getHours()'
var m = mydate.getMinutes();
var ampm = h >= 12 ? 'pm' : 'am';
if(h == 24){
h = 0;
} else if (h > 12 ){
h = h - 0;
}
if(h < 10){
h = "0" + h;
}
if(m < 10){
m = "0" + m;
}
// Return the result. Added some spaces to pretty it up a bit
return ("It is currently "+h+":"+m+ampm+" on "+dayarray[day]+" "+ montharray[month]+" "+daym);
}
// Now output the return value of the function.
document.write(renderTime());
I am trying to get Days,hours from two dates.I searched for the solution and try some code like below but none of them returns the correct days with hours like 2 days ,3 hours.My fields values are like :
d1 = '2014-10-09 08:10:56';
d2 ='2014-11-09 10:10:56';
var dateDiff = function ( d1, d2 ) {
var diff = Math.abs(d1 - d2);
if (Math.floor(diff/86400000)) {
return Math.floor(diff/86400000) + " days";
} else if (Math.floor(diff/3600000)) {
return Math.floor(diff/3600000) + " hours";
} else if (Math.floor(diff/60000)) {
return Math.floor(diff/60000) + " minutes";
} else {
return "< 1 minute";
}
};
function DateDiff(date1, date2) {
var msMinute = 60*1000,
msDay = 60*60*24*1000,
c = new Date(), /* now */
d = new Date(c.getTime() + msDay - msMinute);
return Math.floor(((date2 - date1) % msDay) / msMinute) + ' full minutes between'; //Convert values days and return value
}
what am i doing wrong.Any help thanks
Have you converted d1, d2 to Date object before calling the function dateDiff? Because if you haven't, this line var diff = Math.abs(d1 - d2); won't work as expected.
UPDATE:
I'am assuming your d1 and d2 are in "Y-m-d H:S:M" format, try this:
function parseDate(str){
var tmp = str.split(' ');
var d = tmp[0].split('-');
var t = tmp[1].split(':');
return new Date(d[0], d[1]-1, d[2], t[0], t[1], t[2]);
}
function dateDiff(d1, d2){
d1 = parseDate(d1);
d2 = parseDate(d2);
// ...
// Your code continues
}
I wish I could make it simpler... But this seems to work.
var d1 = '2014-10-09 08:10:58',
d2 ='2015-10-09 08:10:50';
function getDateFromString(str) {
var regexDate = /([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/,
values = regexDate.exec(str);
return new Date(values[1], values[2], values[3], values[4], values[5], values[6]);
}
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}
function dateDiff(d1,d2){
if (d1.getTime() > d2.getTime()) {
var oldD1 = d1;
d1 = d2;
d2 = oldD1;
}
var yearDiff = d2.getFullYear() - d1.getFullYear(),
monthDiff = d2.getMonth() - d1.getMonth(),
dayDiff = d2.getDate() - d1.getDate(),
hourDiff = d2.getHours() - d1.getHours(),
minDiff = d2.getMinutes() - d1.getMinutes(),
secDiff = d2.getSeconds() - d1.getSeconds();
if (secDiff < 0) {
secDiff = 60 + secDiff;
minDiff--;
}
if (minDiff < 0) {
minDiff = 60 + minDiff;
hourDiff--;
}
if (hourDiff < 0) {
hourDiff = 24 + hourDiff;
dayDiff--;
}
if (dayDiff < 0) {
var days = daysInMonth(date2.getMonth(), date2.getFullYear());
dayDiff = days + dayDiff;
monthDiff--;
}
if (monthDiff < 0) {
monthDiff = 12 + monthDiff;
yearDiff--;
}
var diff = yearDiff > 0 ? yearDiff + " years " : "";
diff += monthDiff > 0 ? monthDiff + " months " : "";
diff += dayDiff > 0 ? dayDiff + " days " : "";
diff += hourDiff > 0 ? hourDiff + " hours " : "";
diff += minDiff > 0 ? minDiff + " minutes " : "";
diff += secDiff > 0 ? secDiff + " seconds " : "";
return diff;
}
var date1 = getDateFromString(d1),
date2 = getDateFromString(d2)
document.getElementById('test').innerHTML += date1 + "<br />" + date2;
document.getElementById('test').innerHTML += "<br />" + dateDiff(date1, date2);
console.log(dateDiff(date1, date2));
See JSFiddle
It works in all browsers.
Try this - >
d1 = '2014-10-09 08:10:56';
d2 = '2014-11-09 10:10:56';
var diff = dateDiff(d1,d2);
alert(diff);
function splitDate(d1){
var dSplit = d1.split(' ');
d = dSplit[0] + 'T' + dSplit[1];
return d;
}
function dateDiff(d1,d2){
d1 = splitDate(d1);
d2 = splitDate(d2);
var date1 = new Date(d1);
var date2 = new Date(d2);
var dateDiff = new Date(date2 - date1);
var diff = "Month " + dateDiff.getMonth() + ", Days " + dateDiff.getDay() + ", Hours " + dateDiff.getHours();
return diff;
}
I am assuming you want the difference between 2 dates.
var dateDiff = function(d1/*String*/, d2/*String*/){
var date1 = new Date(d1);
var date2 = new Date(d2);
var result = {
negative:false
};
var diff = date1-date2;
if(diff<0){
result.negative = true;
diff*=-1;
}
result.milliseconds = diff%1000;
diff-=result.milliseconds;
diff/=1000;
result.seconds = diff%60;
diff-=result.seconds
diff/=60;
result.minutes = diff%60;
diff-=result.minutes
diff/=60;
result.hours = diff%24;
diff-=result.hours
result.days= diff/=24;
//And so on
return result;
}
I'm not sure if I really understood but I think this is what you want : http://jsfiddle.net/OxyDesign/927n0L34/
JS
var difference = toDaysAndHours('2014-10-09 08:10:56','2014-11-09 10:10:56');
function toDaysAndHours(d1,d2){
var dif, hours, days, difString = '';
d1 = new Date(d1);
d2 = new Date(d2);
dif = Math.abs(d1 - d2);
hours = (dif/(1000*60*60)).toFixed(0);
days = (hours/24).toFixed(0);
hours = hours - days*24;
difString = days+' days, '+hours+' hours';
return difString;
}
In the first function you are using strings not dates. to properly initialize a date use the constructor, as in:
d1 = new Date('2014-10-09 08:10:56')
d2 = new Date('2014-11-09 10:10:56')
Then on d1 and d2 you can use all of the get*/set* methods specified here: http://www.w3schools.com/jsref/jsref_obj_date.asp
While I got distracted writing the answer, I see others have said similar things, but I will add this:
The data object approach is good for understanding things, but if you want to save time use http://momentjs.com/ or a similar module to save time and mistakes.
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;
};
I need to know the percentage remaining between two dates.
I've used this code:
$(function () {
var end = $('#data').text();
var formattedDate = new Date();
var day = formattedDate.getDate();
var month = formattedDate.getMonth();
month += 1;
var year = formattedDate.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var today = day + "/" + month + "/" + year;
remaining = Math.round(((end - today) * 100) / today));
alert(remaining);
});
But it does'nt work.
Any suggestion?
Thanks
You're subtracting two strings, which is why it won't work.
Subtract two Date objects instead, and you'll get the milliseconds between them (ignoring the maths as to what you define as a % of 2 dates).
var now = new Date();
var then = new Date($('#data').text());
var remaining = Math.round(((then - now) * 100) / now);
You can still, of course, get your formatted string of DD/MM/YY via;
var formattedDays = (now.getDay() < 10 ? "0" : "") + now.getDay();
var formattedMonth = (now.getMonth() < 9 ? "0" : "") + (now.getMonth() + 1);
var formattedDate = formattedDays + "/" + formattedMonth + "/" + now.getFullYear();
Note that you have an extra closing parenthesis at the end of your Math.round() line as well.