Get dates of next 8 Saturdays (javascript) - javascript

I was able to get date of closest Saturday - CodePen
Need help with finding dates of the next seven saturdays.
Thank you
function myFunction(x){
var now = new Date();
now.setDate(now.getDate() + (x+(7-now.getDay())) % 7);
document.getElementById("1s").innerHTML = now.getDate() + ' of ' + now.getMonth() + 'th';
}

Just add 7 days to the date you got and loop desired number of weeks ahead.
function myFunction(x){
var now = new Date();
now.setDate(now.getDate() + (x+(7-now.getDay())) % 7);
document.getElementById("1s").innerHTML = now.getDate() + ' of ' + now.getMonth() + 'th';
var newDate = now;
for (var i = 2; i <= 8; i++) {
var numberOfDaysToAdd = 7;
newDate.setDate(newDate.getDate() + numberOfDaysToAdd);
document.getElementById("" + i + "s").innerHTML = newDate.getDate() + ' of ' + newDate.getMonth() + 'th';
}
}
Forked codepen

Related

How to Add 12 Hours to Current Date?

How to add 12 hours to the current display date? I want to have a promotional offer on my website, this promotional offer will close 12 hours from the current time.
People from different countries with different time slots will visit this, So it has to suffice to their time slot. How can I achieve this?
<html>
<font size="+1.5"><p id="date"></p></font>
<script>
n = new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
</script>
</html>
You can use setTime(), like this example:
n = new Date();
n.setTime(n.getTime() + (12 * 60 * 60 * 1000));
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
h = n.getHours();
mi = n.getMinutes();
document.getElementById("date").innerHTML = m + "/" + d + "/" + y + " " + h + ":" + mi;
<html>
<font size="+1.5"><p id="date"></p></font>
</html>
Try this
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
Just call addHourse function on new Date() and pass number of hours you want to add. For example
alert(new Date().addHours(12));
Okay. here is the full code.
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
}
function getFormattedDate(date) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return month + '/' + day + '/' + year;
}
var date = getFormattedDate(new Date().addHours(12));
var date2 = new Date().addHours(12);
document.getElementById("date").innerHTML = date;
document.getElementById("date2").innerHTML = date2;
<html>
<font size="+1.5">
<p id="date"></p>
</font>
<font size="+1.5">
<p id="date2"></p>
</font>
</html>
This will print the formatted date and date in the default format. You can go with whatever you like.

convert time to to 12 hour by manipulate string

"2015-06-23 14:00:00"
I tried to format above date time into 12 hour base but stuck in somewhere.
function formatDate(raw_date){
var right = raw_date.substring(10, 0);
var hours = ((right[0].substring(2,0) + 11) % 12 + 1);
var min = raw_date.substring(14,16);
var suffix = right[1] >= 12 ? "PM":"AM";
right[1] = ((right[1] + 11) % 12 + 1) + suffix;
return hours + ':' + min + ' ' + suffix;
}
Can someone help? My desired output is "23/06/2015 02:00 PM"
Try this:
function formatDate(raw_date) {
var right = new Date(raw_date);
var currentHours = right.getHours();
var timeOfDay = (currentHours < 12) ? "AM" : "PM";
if (currentHours > 12) {
currentHours -= 12;
}
return (right.getDate() + '/' + right.getMonth()+ '/' + right.getFullYear() +" "+ currentHours+ ":"+right.getMinutes() + timeOfDay);
}
alert(formatDate("2015-06-23 14:00:00"));
Demo
Solution based on your code:
function formatDate(raw_date){
var year = raw_date.substring(0,4);
var month = raw_date.substring(5,7);
var day = raw_date.substring(8,10);
var right = raw_date.substring(10);
var hours = ((right.substring(0,3))% 12 );
var min = raw_date.substring(14,16);
var suffix = right.substring(0,3) >= 12 ? "PM":"AM";
return day + "/"+month+"/"+year+" "+hours + ':' + min + ' ' + suffix;
}
You should follow a simple flow.
Try to break down the input -> convert them _> and then sum them up:
function formatDate(raw_date){
var right = raw_date.substring(0, 10);
var year=right.substring(0,4);
var month=right.substring(5,7);
var day=right.substring(8,10);
right=day+"/"+month+"/"+year;
var left=raw_date.substring(11, raw_date.length);
var hours = left.substring(0,2);
var suffix = hours >= 12 ? "PM":"AM";
hours=hours-12;
if(hours<10) hours='0'+hours;
var min = left.substring(3,5);
left=hours+":"+min+" "+suffix;
return right + ' ' + left;
}

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

Time elapsed between dates

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.

javascript date + 7 days

What's wrong with this script?
When I set my clock to say 29/04/2011 it adds 36/4/2011 in the week input! but the correct date should be 6/5/2011
var d = new Date();
var curr_date = d.getDate();
var tomo_date = d.getDate()+1;
var seven_date = d.getDate()+7;
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
var tomorrowsDate =(tomo_date + "/" + curr_month + "/" + curr_year);
var weekDate =(seven_date + "/" + curr_month + "/" + curr_year);
{
jQuery("input[id*='tomorrow']").val(tomorrowsDate);
jQuery("input[id*='week']").val(weekDate);
}
var date = new Date();
date.setDate(date.getDate() + 7);
console.log(date);
And yes, this also works if date.getDate() + 7 is greater than the last day of the month. See MDN for more information.
Without declaration
To return timestamp
new Date().setDate(new Date().getDate() + 7)
To return date
new Date(new Date().setDate(new Date().getDate() + 7))
Something like this?
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
alert(res);
convert to date again:
date = new Date(res);
alert(date)
or alternatively:
date = new Date(res);
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = date.getMinutes();
// seconds part from the timestamp
var seconds = date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = date + '-' + hours + ':' + minutes + ':' + seconds;
alert(formattedTime)
In One line:
new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
The simple way to get a date x days in the future is to increment the date:
function addDays(dateObj, numDays) {
return dateObj.setDate(dateObj.getDate() + numDays);
}
Note that this modifies the supplied date object, e.g.
function addDays(dateObj, numDays) {
dateObj.setDate(dateObj.getDate() + numDays);
return dateObj;
}
var now = new Date();
var tomorrow = addDays(new Date(), 1);
var nextWeek = addDays(new Date(), 7);
alert(
'Today: ' + now +
'\nTomorrow: ' + tomorrow +
'\nNext week: ' + nextWeek
);
Using the Date object's methods will could come in handy.
e.g.:
myDate = new Date();
plusSeven = new Date(myDate.setDate(myDate.getDate() + 7));
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var d = new Date(res);
var month = d.getMonth() + 1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month < 10 ? '0' : '') + month + '/' +
(day < 10 ? '0' : '') + day;
$('#txtEndDate').val(output);
var future = new Date(); // get today date
future.setDate(future.getDate() + 7); // add 7 days
var finalDate = future.getFullYear() +'-'+ ((future.getMonth() + 1) < 10 ? '0' : '') + (future.getMonth() + 1) +'-'+ future.getDate();
console.log(finalDate);
You can add or increase the day of week for the following example and hope this will helpful for you.Lets see....
//Current date
var currentDate = new Date();
//to set Bangladeshi date need to add hour 6
currentDate.setUTCHours(6);
//here 2 is day increament for the date and you can use -2 for decreament day
currentDate.setDate(currentDate.getDate() +parseInt(2));
//formatting date by mm/dd/yyyy
var dateInmmddyyyy = currentDate.getMonth() + 1 + '/' + currentDate.getDate() + '/' + currentDate.getFullYear();
Two problems here:
seven_date is a number, not a date. 29 + 7 = 36
getMonth returns a zero based index of the month. So adding one just gets you the current month number.

Categories

Resources