Javascript calendar displaying month and days - javascript

I'm trying to display a calendar where the month and year show at the top, with the days on single line (number line format) below. I want to get the next and previous months after clicking a button.
However, it only works after one click and I cant get the correct amount of days to display for the month.
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var d = new Date();
var label = month[d.getMonth()];
var year = d.getFullYear();
var day = d.getDate();
document.getElementById("mon").innerHTML = label + " " + year;
document.getElementById("days").innerHTML = day;
//display days
var daysInMonths = [31, (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
document.getElementById("prevBtn").addEventListener("click", previousMonth);
function previousMonth() {
label = month[d.getMonth() - 1];
document.getElementById("mon").innerHTML = label + " " + year;
}
document.getElementById("nextBtn").addEventListener("click", nextMonth);
function nextMonth() {
label = month[d.getMonth() + 1];
if (label > 11) {
year = d.getFullYear() + 1;
}
document.getElementById("mon").innerHTML = label + " " + year;
}
<div class="calendar">
<div class="header">
<span class="left button" id="prevBtn">〈</span>
<span><h1 id="mon"></h1></span>
<span class="right button" id="nextBtn">〉</span>
</div>
<table>
<tbody>
<tr id="days"></tr>
</tbody>
</table>
</div>

I've made a few modifications below as per my comment above.
var month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var today = new Date();
var label = month[today.getMonth()];
var mm = today.getMonth(); // keep track of the month
var year = today.getFullYear(); // keep track of the year
var day = today.getDate();
document.getElementById("mon").innerHTML = label + " " + year;
document.getElementById("days").innerHTML = day;
//display days
var daysInMonths = [31, (((year%4==0)&&(year%100!=0))||(year%400==0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
document.getElementById("prevBtn").addEventListener("click", previousMonth);
function previousMonth() {
mm -= 1; // decrement the month
if (mm < 0) { // if we go before January
mm = 11; // go to December
year -= 1; // of previous year
}
label = month[mm];
document.getElementById("mon").innerHTML = label + " " + year;
}
document.getElementById("nextBtn").addEventListener("click", nextMonth);
function nextMonth(){
mm += 1; // increment month
if (mm > 11) { // if we go after December
mm = 0; // go to January
year += 1; // of next year
}
document.getElementById("mon").innerHTML = label + " " + year;
}

Related

Determine the calendar week for a given Date

I tried to search for "Calculating the Week for a given Date" and could not find accurate solution in a easier way. Here is what I have tried:
Let's assume the date specified is 'd'
getWeekOfDay: function(d){
var date1 = new Date(d.getFullYear(), d.getMonth(), d.getDate());
var yearWeek;
var firstMondayOfWeek1 =
this.getMondayOfWeekOneOfAGivenYear(date1.getFullYear());
var weekNumber = Math.ceil((((date1 - firstMondayOfWeek1) / 86400000) + 1) / 7);
yearWeek = date1.getFullYear() + "." + weekNumber;
if(weekNumber <= 0 ){ // Jan 01 2012;
//date falls in last week of previous year
firstMondayOfWeek1 = this.getMondayOfWeekOneOfAGivenYear(date1.getFullYear() - 1);
weekNumber = Math.ceil((((date1 - firstMondayOfWeek1) / 86400000) + 1) / 7);
yearWeek = (date1.getFullYear() - 1) + "." + weekNumber;
}
if(weekNumber === 53 ){ // Dec 29 2014; Dec 28 2020
var Dec31 = new Date(date1.getFullYear(), 11, 31);
if(Dec31.getDay() < 4){
yearWeek = (date1.getFullYear() + 1) + "." + 1;
}
}
return yearWeek;
},
getMondayOfWeekOneOfAGivenYear: function(year){
//4th Jan always falls in Week1 of that year
var fouthJan = new Date(year, 0, 4);//
var day = fouthJan.getDay();
if (fouthJan.getDay() === 0) { //Sunday
day = 7;
}
var firstMondayofW1 = new Date(fouthJan);
firstMondayofW1.setDate(firstMondayofW1.getDate() + (1 - day) * 1);
return firstMondayofW1;
},

How to return the correct months?

First date should be 28/03/2017 but it's returning as 28/02/2017.
The months after the first date seems to be correct.
Is there a better way of doing this or can someone help me figure out why the first date is acting like it is?
var date = new Date("Tue Mar 28 2017 13:14:00 GMT+0100 (BST)");
var additionalMonth = date.getMonth();
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function formatDateToString(d){
var month = '' + (d.getMonth() + 1);
var day = '' + d.getDate();
var year = d.getFullYear();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
hour = addZero(hour);
minute = addZero(minute);
second = addZero(second);
var date = [day, month, year].join('/');
var time = [hour, minute, second].join(':');
var newDate = date + " " + time;
return newDate;
}
function setTimeForDate(date){
date.setHours(12);
date.setMinutes(0);
date.setSeconds(0);
return date;
}
function calculateDate(date, month){
date.setMonth(month);
date = setTimeForDate(date);
return date;
}
function calculateLastDayMonth(date, day){
var month = date.getMonth();
var year = date.getFullYear();
var d = new Date(year, month, 0).getDate();
if(day >= d){
date = new Date(year, month, 0);
}
date = setTimeForDate(date);
return date;
}
function returnFormattedDate(startDate, additionalMonth){
var day = startDate.getDate();
var newDate = calculateDate(startDate, additionalMonth);
var correctDate = calculateLastDayMonth(newDate, day);
return formatDateToString(correctDate);
}
$(".returnedDate").text("START DATE: " + returnFormattedDate(date, additionalMonth));
for(var x = 0; x <= 5; x++){
$("body").append(returnFormattedDate(date, additionalMonth) + "<br>");
additionalMonth++;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h5 class="returnedDate"></h5>
You have to change var month = date.getMonth(); to var month = date.getMonth()+1; because the index starts from 0.
var date = new Date("Tue Mar 28 2017 13:14:00 GMT+0100 (BST)");
var additionalMonth = date.getMonth();
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function formatDateToString(d){
var month = '' + (d.getMonth() + 1);
var day = '' + d.getDate();
var year = d.getFullYear();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
hour = addZero(hour);
minute = addZero(minute);
second = addZero(second);
var date = [day, month, year].join('/');
var time = [hour, minute, second].join(':');
var newDate = date + " " + time;
return newDate;
}
function setTimeForDate(date){
date.setHours(12);
date.setMinutes(0);
date.setSeconds(0);
return date;
}
function calculateDate(date, month){
date.setMonth(month);
date = setTimeForDate(date);
return date;
}
function calculateLastDayMonth(date, day){
var month = date.getMonth()+1;
var year = date.getFullYear();
var d = new Date(year, month, 0).getDate();
if(day >= d){
date = new Date(year, month, 0);
}
date = setTimeForDate(date);
return date;
}
function returnFormattedDate(startDate, additionalMonth){
var day = startDate.getDate();
var newDate = calculateDate(startDate, additionalMonth);
var correctDate = calculateLastDayMonth(newDate, day);
return formatDateToString(correctDate);
}
$(".returnedDate").text("START DATE: " + returnFormattedDate(date, additionalMonth));
for(var x = 0; x <= 5; x++){
$("body").append(returnFormattedDate(date, additionalMonth) + "<br>");
additionalMonth++;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h5 class="returnedDate"></h5>
You have 2 different approaches:
var additionalMonth = date.getMonth();
and
var month = '' + (d.getMonth() + 1);
JS returns months counting from 0, so for January it's 0, 1 for February, etc., so if you want proper number you need to add 1, as you do for month. You can check this out here as well.
var month = date.getMonth() + 1;
You should add 1 to the month because the month indexing starts with 0;
Please change the line in calculateLastDayMonth() function.
var month = date.getMonth()+1; i.e you need to add +1 it works fine
Please find the updated code mentioned below:
var date = new Date("Tue Mar 28 2017 13:14:00 GMT+0100 (BST)");
var additionalMonth = date.getMonth();
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function formatDateToString(d){
var month = '' + (d.getMonth() + 1);
var day = '' + d.getDate();
var year = d.getFullYear();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
hour = addZero(hour);
minute = addZero(minute);
second = addZero(second);
var date = [day, month, year].join('/');
var time = [hour, minute, second].join(':');
var newDate = date + " " + time;
return newDate;
}
function setTimeForDate(date){
date.setHours(12);
date.setMinutes(0);
date.setSeconds(0);
return date;
}
function calculateDate(date, month){
date.setMonth(month);
date = setTimeForDate(date);
return date;
}
function calculateLastDayMonth(date, day){
var month = date.getMonth()+1;
var year = date.getFullYear();
var d = new Date(year, month, 0).getDate();
if(day >= d){
date = new Date(year, month, 0);
}
date = setTimeForDate(date);
return date;
}
function returnFormattedDate(startDate, additionalMonth){
var day = startDate.getDate();
var newDate = calculateDate(startDate, additionalMonth);
var correctDate = calculateLastDayMonth(newDate, day);
return formatDateToString(correctDate);
}
$(".returnedDate").text("START DATE: " + returnFormattedDate(date, additionalMonth));
for(var x = 0; x <= 5; x++){
$("body").append(returnFormattedDate(date, additionalMonth) + "<br>");
additionalMonth++;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h5 class="returnedDate"></h5>

Getting a date range adjust to days

I have this date functionality that gets date range of six months, taking into consideration if the range has passed to a new year. How can i alter this date function to take a range of 15 days,while taking into consideration if the range has passed to a new months and/or a new year.
var dt = new Date();
var month = new Array();
month[0] = "JAN";
month[1] = "FEB";
month[2] = "MAR";
month[3] = "APR";
month[4] = "MAY";
month[5] = "JUNE";
month[6] = "JULY";
month[7] = "AUG";
month[8] = "SEPT";
month[9] = "OCT";
month[10] = "NOV";
month[11] = "DEC";
var tmonth = dt.getMonth() + 6 <= 11 ? dt.getMonth() + 6 : dt.getMonth() - 6;
var tyear = dt.getMonth() + 6 <= 11 ? dt.getFullYear() : dt.getFullYear() + 1;
var eom = new Date(tyear, tmonth + 1, 0).getDate(); //get last day of the month
var tday = dt.getDate() > eom ? eom : dt.getDate(); //check if the from day of month > last day of month
var frm = dt.getDate() + '-' + month[dt.getMonth()] + '-' + dt.getFullYear().toString().substr(2, 2);
var till = tday + '-' + month[tmonth] + '-' + tyear.toString().substr(2, 2);
I think the solution to this would be:
var dt = new Date();
var month = new Array();
month[0] = "JAN";
month[1] = "FEB";
month[2] = "MAR";
month[3] = "APR";
month[4] = "MAY";
month[5] = "JUNE";
month[6] = "JULY";
month[7] = "AUG";
month[8] = "SEPT";
month[9] = "OCT";
month[10] = "NOV";
month[11] = "DEC";
var range = 15;
var tmonth = dt.getMonth() + (range % 12) <= 11 ? dt.getMonth() + (range % 12) : dt.getMonth() - 6;
var tyear = dt.getMonth() + (range % 12) <= 11 ? dt.getFullYear() + Math.floor(range/12) : dt.getFullYear() + Math.floor(range/12) + 1;
var eom = new Date(tyear, tmonth + 1, 0).getDate(); //get last day of the month
var tday = dt.getDate() > eom ? eom : dt.getDate(); //check if the from day of month > last day of month
var frm = dt.getDate() + '-' + month[dt.getMonth()] + '-' + dt.getFullYear().toString().substr(2, 2);
var till = tday + '-' + month[tmonth] + '-' + tyear.toString().substr(2, 2);
Now you can choose any range you want - whether it's 6 or 15.

Delivery Date Javascript Adapt To Exclude Weekends

I have been currently using this script
<script type="text/javascript">
var _next = new Date(new Date() * 1 + 24*60*60*1000*9);
document.write(" Your expected delivery date is " + (_next.getMonth() + 1) + "/" + _next.getDate() + "/" + _next.getFullYear());
</script>
I'm wondering how do I get it to exclude weekends if possible.
Just add hours if you like. this is a code that expects to deliver the next working day.
function myFunction() {
var d = new Date();
var weekday = new Array(7);
weekday[0] = "sunday";
weekday[1] = "monday";
weekday[2] = "tuesday";
weekday[3] = "wednesday";
weekday[4] = "thursday";
weekday[5] = "friday";
weekday[6] = "saturday";
var monthday = new Array(12);
monthday[0] = "01";
monthday[1] = "02";
monthday[2] = "03";
monthday[3] = "04";
monthday[4] = "05";
monthday[5] = "06";
monthday[6] = "07";
monthday[7] = "08";
monthday[8] = "09";
monthday[9] = "10";
monthday[10] = "11";
monthday[11] = "12";
if (d.getDay() > 0 && d.getDay() <= 4) {
d.setHours(d.getHours() + 24);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
} else if (d.getDay() == 0) {
d.setHours(d.getHours() + 48);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
} else {
d.setHours(d.getHours() + 72);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
}
}
myFunction()
<script type="text/javascript">
<!--
var myDate=new Date();
if ( myDate.getHours() < 12 ) // less than 12pm
{
var daystodeliver = [7,5,5,5,5,8,7][myDate.getDay()];
}
else
{
var daystodeliver = [7,7,7,7,7,9,8][myDate.getDay()];
}
myDate.setDate(myDate.getDate()+daystodeliver);
document.write(['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'] [myDate.getDay()]);
var dayofmonth = myDate.getDate();
suffix = ((dayofmonth < 10)||(dayofmonth > 20)) ? ['th','st','nd','rd','th','th','th','th','th','th'][dayofmonth % 10] : 'th';
document.write(' ' + dayofmonth + suffix + ' ');
document.write(['January','February','March','April','May','June','July','August','Septembe r','October','November','December'][myDate.getMonth()]);
// -->
Try this:
function deliver(inDays, startingOn){
var s, f = 0, d;
if(!inDays)inDays = 0;
s = !startingOn ? new Date : new Date(startingOn);
for(var i=0,n,t=0,l=inDays; i<l; i++,t+=86400000){
n = new Date(s.getTime()+t).getDay();
if(n === 0 || n === 6)f++;
}
d = new Date(s.getTime()+86400000*(inDays+f));
return 'Your expected delivery date is '+d.toLocaleDateString();
}
// same day delivery
console.log(deliver());
// deliver in 9 days stating today
console.log(deliver(9));
// deliver in 9 days starting on October 12, 2013 - must be a valid Date String
console.log(deliver(9, 'October 12, 2013'));
/* Note that in the last example the Date starts on the weekend, therefore same
day becomes Monday, which if you don't work weekends is the first day you
would see the order anyways.
*/
This is good to show your Client when something is delivered. Make sure you set the actual date it your database, according to where you are, using a Server Side language like PHP.
You should pay me for this since it will work even on a leap year. Ha!
Try this to get the date
I wrote a routine that you supply a date object, apply the menthod, the public holidays in a separate list is passed and any holidays / public holidays including weekends are skipped over.
Its this post
// array of ISO YYYY-MM-DD format dates
publicHolidays = {
uk:["2020-01-01","2020-04-10","2020-04-13","2020-05-08","2020-05-25",
"2020-08-03","2020-08-31","2020-12-25","2020-12-28"],
usa:["2020-01-01","2020-01-20","2020-02-14","2020-02-17","2020-04-10",
"2020-04-12","2020-05-10","2020-05-25","2020-06-21","2020-07-03",
"2020-07-04","2020-09-07","2020-10-12","2020-10-31","2020,11,11",
"2020-11-26","2020-12-25"]
}
// check if there is a match in the array
Date.prototype.isPublicHoliday = function( data ){// we check for a public holiday
if(!data) return 1;
return data.indexOf(this.toISOString().slice(0,10))>-1? 0:1;
}
// calculation of business days
Date.prototype.businessDays = function( d, holidays ){
var holidays = holidays || false, t = new Date( this ); // copy date.
while( d ){ // we loop while d is not zero...
t.setDate( t.getDate() + 1 ); // set a date and test it
switch( t.getDay() ){ // switch is used to allow easier addition of other days of the week
case 0: case 6: break;// sunday & saturday
default: // check if we are a public holiday or not
d -= t.isPublicHoliday( holidays );
}
}
return t.toISOString().slice(0,10); // just the YYY-MM-DD
}
// dummy var, could be a form field input
OrderDate = "2020-02-12";
// test with a UK holiday date
var deliveryDate = new Date(OrderDate).businessDays(7, publicHolidays.usa);
// expected output 2020-02-25
console.log("Order date: %s, Delivery date: %s",OrderDate,deliveryDate );

validate a dropdown list to get proper date based on the option selected

- I have a dropdown List on which there are some options from which user can select one.
- Options are 1 day, 1 week, 2 weeks, 1 month and 6 months
- Now when I select option 1 day, today's date should be incremented by one and next date is shown.
- If I select 1 week, the date falling after one week should be shown.
- Now the problem is when I select an option it sometimes shows date greater than 30/31.
- I use below javacript function:
function select_duration(ddlcupon) {
var skillsSelect = document.getElementById("ddlcupon");
var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
if (selectedText == "1 Day") {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + 1;
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "1 Week") {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + 7;
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "2 Weeks") {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + 14;
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "1 Month") {
var currentTime = new Date();
var month = currentTime.getMonth() + 2;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "6 Months") {
var currentTime = new Date();
var month = currentTime.getMonth() + 7;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
- Can someone help me in getting a proper date?
try using this
var dt1 = new Date();
var dt2 = new Date(dt1.getTime() + (86400000 * numberOfDay) );
if your date is incremented by one day try
var dt2 = new Date(dt1.getTime() + (86400000 * 1 ) ); //so on
The problem is you're incrementing day, month and year. So, if the month is 12, you'll get 13. You could work directly with milliseconds. For example:
var d = new Date('01/31/2013'); // Thu Jan 31 2013 00:00:00 GMT-0200 (BRST)
var addDay = 1000 * 60 * 60 * 24;
var currentMs = d.getTime();
d.setTime(currentMs + addDay);
console.log(d); // Fri Feb 01 2013 00:00:00 GMT-0200 (BRST)
Date.js is a handy script for all kinds of JavaScript date manipulation.
The syntax to add n number of days to current day is
// Add 3 days to Today
Date.today().add(3).days();
In this case adds 3 days to the current date.

Categories

Resources