Javascript getMonth() and getDate transions issuse - javascript

Hello i am trying to write the following function to display 7 days of the week
function displaydates(){
// read the string output from the datepicker and
//evalutes which date goes into which cell
var date = document.getElementById("datepicker"); // Mon APR 30 2012 HH:MM:SS
var m = new Date(date.value);
var num = parseInt(m.getDate());
var i = 0;
var days=[];
var x;
for(i; i<=6; i++){
var day= m.setDate(num+i);
var month = m.setMonth(m.getMonth());
x = m.getMonth()+1 + "/" + m.getDate() + "<br />";
days.push(x);
}
document.getElementById("Monday").innerHTML= days[0];
document.getElementById("Tuesday").innerHTML=days[1];
document.getElementById("Wednesday").innerHTML=days[2];
document.getElementById("Thursday").innerHTML=days[3];
document.getElementById("Friday").innerHTML=days[4];
document.getElementById("Saturday").innerHTML=days[5];
document.getElementById("Sunday").innerHTML=days[6];
}
the code works fine as long as it's seven days before the next month.the problem i am having is when the user wants to see the next seven day the function outputs the wrong information
for example
var m = new Date("Apr 30 2012"); / /monday
will make my function out put the following
4/29, 5/30, 7/1, 9/1, 11/2, 1/3, 3/7
again, this only happens on transition to the next month is there and thing i can do to make the month to month transition work in my function

When you call, for example, setDate(32), JavaScript figures out that that requires an additional month and adds it to the date. When you later call setDate(33), it once again adds an extra month...
This solution might work better (some parts are omitted):
var start = new Date();
var days = [];
for(var i = 0; i <= 6; ++i) {
var str = (start.getMonth() + 1) + '/' + start.getDate() + '<br />';
days.push(str);
start.setDate(start.getDate() + 1);
}

Please use the below provided solution
function displaydates(){
// read the string output from the datepicker and
//evalutes which date goes into which cell
var date = document.getElementById("datepicker"); // Mon APR 30 2012 HH:MM:SS
var m = new Date(date.value);
var num = m.getTime();
var i = 0;
var days=[];
var x;
for(i; i<=6; i++){
num+=86400000; //Edited Part
m = new Date(num);
var day= m.getDate();
var month = m.getMonth();
x = month+1 + "/" + day + "<br />";
days.push(x);
}
document.getElementById("Monday").innerHTML= days[0];
document.getElementById("Tuesday").innerHTML=days[1];
document.getElementById("Wednesday").innerHTML=days[2];
document.getElementById("Thursday").innerHTML=days[3];
document.getElementById("Friday").innerHTML=days[4];
document.getElementById("Saturday").innerHTML=days[5];
document.getElementById("Sunday").innerHTML=days[6];
}
Hope this solves your problem.

Related

How to get the last months and years from current date

I want to create the JSON formatted as shown below, in decreasing order starting from current date (it will be the actual current date).
var theMonths = [
{"date":"2015-12","value":null}, {"date":"2016-01","value":null},
{"date":"2016-02","value":null}, {"date":"2016-03","value":null},
{"date":"2016-04","value":null}, {"date":"2016-05","value":null},
{"date":"2016-06","value":null}, {"date":"2016-07","value":null},
{"date":"2016-08","value":null}, {"date":"2016-09","value":null},
{"date":"2016-10","value":null}, {"date":"2016-11","value":null},
{"date":"2016-12","value":null}, {"date":"2017-01","value":null},
{"date":"2017-02","value":null}, {"date":"2017-03","value":null},
{"date":"2017-04","value":null}, {"date":"2017-05","value":null}
]
I want to pass this data in a chart.
var dateFromPast = [];
var amountOfDatesFromPast = 18;
for (var i = 0; i < amountOfDatesFromPast; i++){
var dateObj = new Date();
dateObj.setMonth(dateObj.getMonth() - i);
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var year = dateObj.getUTCFullYear();
newdate = year + "-" + month;
dateFromPast.push(newdate);
}
console.log(dateFromPast);

How to loop between dates that are in dmy format

Here is my 2 date
var startdate = '11-12-2016';
var stopdate = '13-12-2016';
I want to loop between these two dates. So, i did like this
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
while(startMedicine <= stopMedicine){
console.log(startdate)
}
But i am getting unlimited loops running in browser.
How can i do this.
Note :
I don't want to use jQuery for this one.
If the start and end date is same it should loop only once and the input date will be always d/m/y format. What is the mistake in my code. Pls help
Update :
I have mistaken the date format, my date format is d-m-y. How can i do this for one..
Increment date by one day per iteration using getDate
startdateArr = startdate.split('-');
stopdateArr = stopdate.split('-');
var startMedicine = new Date(startdateArr[2],startdateArr[1]-1,startdateArr[0]);
var stopMedicine = new Date(stopdateArr[2],stopdateArr[1]-1,stopdateArr[0]);
// thanks RobG for correcting on month index
while(startMedicine <= stopMedicine){
var v = startMedicine.getDate() + '-' + (startMedicine.getMonth() + 1) + '-' + startMedicine.getFullYear();
console.log(v);
startMedicine.setDate(startMedicine.getDate()+1);
}
In js month indexing starts at 0 so nov is 10 dec. is 11 and like so that's why i use getMonth() + 1
`
main problem is that you are not increasing your date.
here is the solution
var startdate = '11/12/2016';
var stopdate = '11/13/2016';
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
var currentMedicine = startMedicine;
var dayCount = 0;
while(currentMedicine < stopMedicine){
currentMedicine.setDate(startMedicine.getDate() + dayCount);
// You can replace '/' to '-' this if you want to have dd-mm-yyyy instead of dd/mm/yyy
var currentDate = currentMedicine.getDate() + '/' + (currentMedicine.getMonth() + 1) + '/' + currentMedicine.getFullYear(); // in dd/mm/yyyy format
console.log(currentDate);
dayCount++;
}
You can make use of moment js and moment js duration. Its for duration purpose only. It very easy and meant for same.

Get previous and next weeks from a calendar using JavaScript

I want to make a week planner, that displays all days of the week and the according date to it. And of course the month.
(Unfortunately, I don't have enough reputation to post a screenshot of what my calendar looks like.)
My JavaScript code looks like this. I found a part of it from Stack Overflow.
function calendar() {
var today = new Date();
var currYear = today.getFullYear();
var currMonth = today.getMonth();
var currWeek = today.getWeek()-1;
var firstDateOfMonth = new Date(currYear, currMonth, 1);
var firstDayOfMonth = firstDateOfMonth.getDay();
var firstDateOfWeek = new Date(firstDateOfMonth);
firstDateOfWeek.setDate(
firstDateOfWeek.getDate() +
(firstDayOfMonth ? 7 - firstDayOfMonth : 0)
);
firstDateOfWeek.setDate(
firstDateOfWeek.getDate() +
7 * (currWeek-1)
);
var dateNumbersOfMonthOnWeek = [];
var datesOfMonthOnWeek = [];
for (var i = 0; i < 7; i++) {
dateNumbersOfMonthOnWeek.push(
firstDateOfWeek.getDate());
datesOfMonthOnWeek.push(
new Date(+firstDateOfWeek));
firstDateOfWeek.setDate(
firstDateOfWeek.getDate() + 1);
}
setText('month-year', monthArray[currMonth] + " " + currYear);
setText('Mo', dateNumbersOfMonthOnWeek[0]);
setText('Di', dateNumbersOfMonthOnWeek[1]);
setText('Mi', dateNumbersOfMonthOnWeek[2]);
setText('Do', dateNumbersOfMonthOnWeek[3]);
setText('Fr', dateNumbersOfMonthOnWeek[4]);
setText('Sa', dateNumbersOfMonthOnWeek[5]);
setText('So', dateNumbersOfMonthOnWeek[6]);
};
function setText(id, val) {
if(val < 10){
val = '0' + val;
}
document.getElementById(id).innerHTML = val;
};
window.onload = calendar;
It works as it displays the correct days for the weekdays (so, 08 for this Monday, 09 for this Tuesdays, etc) and also the month is the correct one.
The question now is how to get the previous or next week? When I click on the "<" arrow I want to see the previous week. So how should I write the loop, which parameters does the method need, etc. I am very thankful for every hint, link, example etc.
For next week-
var today = new Date();
var nextweek = new Date(today.getFullYear(), today.getMonth(), today.getDate()+7);
for more detail check following link:-
how to get next week date in javascript

if condition based on a string in for loop in jquery

I will explain my question in the code itself. Please see the below code
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
for (var i = 0, length = dynmonths.length; i < length; i++) {
var month = '01-' + dynmonths[i] + '-' + strcurrent;
}
But the problem is that month is taking 14for all the months. Which is wrong. After 01-DEC-14 the next month must be 01-JAN-15, 01-FEB-15 and so on. How to check DEC in for loop and after DEC year must change to year+1
Thanks in advance
use below code it will work.
function ddd()
{
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
for (var i = 0, length = dynmonths.length; i < length; i++) {
if(dynmonths[i]=='JAN')
{
var str = parseInt(str)+parseInt(1);
}
var month = '01-' + dynmonths[i] + '-' + str;
document.writeln(month);
document.write("<br />");
}
}
<body onload="ddd()">
You can declare variable bool = false and check if you on DEC change it to true (or use counter from more then one year):
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
var isPassYear = false;
for (var i = 0, length = dynmonths.length; i < length; i++) {
var month;
if (isPassYear)
//do something
else
month = '01-' + dynmonths[i] + '-' + strcurrent;
if (monthNames[11] == dynmonths[i]) {
isPassYear = true;
}
}
second option is to use Date object and append his month by one each time, if you set append to month number 12 it automatic go to the next year.

get an array of dates for the past week in format dd_mm

I need to have an array of dates for whole days of the last week, including the current day, for e.g
['05/06', '04/06', '03/06', '02/06', '01/06', '31/05', '30/05']
(format dd/mm)
how can i do this?
I know there is the Date() object, but other than that I'm stumped.
logic along the lines of:
var dates = [];
var today = new Date();
for (var i = 0; i<7; i++){
var date = today - (i+1);
dates.push(date);
}
So you want an array containing todays date and a further 6 elements, with todays date-1, todays date-2 etc...?
var dates = [];
var date = new Date();
for (var i = 0; i < 7; i++){
var tempDate = new Date();
tempDate.setDate(date.getDate()-i);
var str = tempDate.getDate() + "/" + tempDate.getMonth();
dates.push(str);
}
console.log(dates);
Output: ["5/5", "4/5", "3/5", "2/5", "1/5", "31/4", "30/4"]
If you need numbers with leading 0's, try this:
var dates = [];
var date = new Date();
for (var i = 0; i < 7; i++){
var tempDate = new Date();
tempDate.setDate(date.getDate()-i);
var str = pad(tempDate.getDate()) + "/" + pad(tempDate.getMonth());
dates.push(str);
}
console.log(dates);
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
Output: ["05/05", "04/05", "03/05", "02/05", "01/05", "31/04", "30/04"]
Check this working sample, where all days are printed out:
http://jsfiddle.net/danyu/Tu5R6/6/
This is the main logic:
for(var i=7;i>0;i--)
{
tempDate.setDate(tempDate.getDate()-1);
output+=tempDate+"<br/>";
}
Modify it to store those days into your array.

Categories