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.
Related
I have question about getting full two years from the current date. So what i did id get the current month using the new date function and used the for loop to print each of the month. But, i cant really get it to work.... I will post the code that i did below. I would be really appreciate it if anyone can tell me the logic or better way of doing it.
For example: if today current date is august it store into an array from 8 / 2020 9/ 2020 ..... 12/ 2020, 1/2021 and goes to another year to 8/2022.
var d = new Date();
var year = d.getFullYear();
var dateStr;
var currentYear;
var storeMonthYear = [];
for(var i = 1; i <= 24; i++){
dateStr = d.getMonth() + i
currentYear = year;
if(dateStr > "12"){
dateStr = dateStr - 12
// currentYear = year;
// if(currentYear){
// }
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else if(dateStr > "24"){
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else{
storeMonthYear[i] = dateStr + "/" + currentYear;
}
storeMonthYear[i] = d.getMonth() + i
}
export const settlementPeriod = [
{
MonthYearFirstRow1: storeMonthYear[1],
MonthYearFirstRow2: storeMonthYear[2],
MonthYearFirstRow3: storeMonthYear[3],
MonthYearFirstRow4: storeMonthYear[4],
MonthYearFirstRow5: storeMonthYear[5],
MonthYearFirstRow6: storeMonthYear[6],
MonthYearFirstRow7: storeMonthYear[7],
MonthYearFirstRow8: storeMonthYear[8],
MonthYearFirstRow9: storeMonthYear[9],
MonthYearFirstRow10: storeMonthYear[10],
MonthYearFirstRow11: storeMonthYear[11],
MonthYearFirstRow12: storeMonthYear[12],
MonthYearSecondRow13: storeMonthYear[13],
MonthYearSecondRow14: storeMonthYear[14],
MonthYearSecondRow15: storeMonthYear[15],
MonthYearSecondRow16: storeMonthYear[16],
MonthYearSecondRow17: storeMonthYear[17],
MonthYearSecondRow18: storeMonthYear[18],
MonthYearSecondRow19: storeMonthYear[19],
MonthYearSecondRow20: storeMonthYear[20],
MonthYearSecondRow21: storeMonthYear[21],
MonthYearSecondRow22: storeMonthYear[22],
MonthYearSecondRow23: storeMonthYear[23],
MonthYearSecondRow24: storeMonthYear[24]
},
];
Create the date from today, get the month and year. Iterate from 0 to 24 for now till in 24 months. If month is 12 than set month to 0 and increment the year. Push the new datestring. Increment the month for the next step.
Note: Beacsue JS counts months form 0-11 you had to add for the datestring 1 for the month and make the change of year at 12 and not 13.
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let res=[];
for (let i=0; i<=24; i++) {
if (month===12) {
month = 0;
year++;
}
res.push(month+1 + '/' + year);
month++;
}
console.log(res);
Here you go, you get an array of strings like "8/2020","9/2020" etc from starting month to the last month including both( in total 25 months).
If you don't want to include last month just delete +1 from for loop condition.
let currentDate = new Date();
let settlementPeriod = [];
let numberOfMonths = 24;
for(let i=0;i<numberOfMonths+1;i++){
settlementPeriod.push(currentDate.getMonth()+1+"/"+currentDate.getFullYear()); //We add current date objects attributes to the array
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1)); //Every time we add one month to it
}
console.log(settlementPeriod);
There are a couple of things that stick out in your code sample:
You're comparing strings and numbers (e.g. dateStr > "12"). This will lead to some weird bugs and is one of JS's most easily misused "features". Avoid it where possible.
You increment the year when you reach 12 months from now, rather than when you reach the next January
You're overwriting your strings with this line storeMonthYear[i] = d.getMonth() + i so your array is a bunch of numbers rather than date strings like you expect
Here's a code sample that I think does what you're expecting:
function next24Months() {
const today = new Date()
let year = today.getFullYear()
let monthIndex = today.getMonth()
let dates = []
while (dates.length < 24) {
dates.push(`${monthIndex + 1}/${year}`)
// increment the month, and if we're past December,
// we need to set the year forward and the month back
// to January
if (++monthIndex > 11) {
monthIndex = 0
year++
}
}
return dates
}
In general, when you're dealing with dates, you're probably better off using a library like Moment.js - dates/times are one of the most difficult programming concepts.
While #Ognjen 's answer is correct it's also a bit waseful if your date never escapes its function.
You don't need a new date every time:
function getPeriods(firstMonth, numPers){
var d = new Date(firstMonth.getTime()); // clone the start to leave firstMonth alone
d.setDate(1); // fix after #RobG
var pers = [];
var m;
for(var i = 0; i< numPers; i++){
m = d.getMonth();
pers.push(`${m+ 1}/${d.getFullYear()}`)
d.setMonth(m + 1); // JS dates automatically roll over. You can do this with d.setDate() as well and when you assign 28, 29, 31 or 32 the month and year roll over automatically
}
return pers;
}
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);
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
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.
I've got this:
var lDate = document.getElementById('txtLeaveDate');
var rDate = document.getElementById('txtReturnedDate');
Err...javascript so how do I assign the value of txtLeaveDate to a date variable
I tried:
var myDate = new Date(lDate.value);
But this assigns some long value....
I can do it if I try:
var today = new Date();
var day2 = new Date();
day2.setDate(today.getDate() + 30);
But the issue is I need to get the date from txtLeaveDate not by a date variable
edit complete code
var theLDate = new Date(lDate.value);
var theRDate = new Date(rDate.value);
//check if return date is a sunday, if it is no need
//to do anything,
//else make it a sunday
while (theRDate.getDay() != 0)
theRDate.setDate(theRDate.getDate() + 1);
//at this point RDate is a sunday...
while(theLDate.valueOf() <= theRDate.valueOf())
{
if(theLDate.getDay() == 0)
{ //sunday
var li = document.createElement('li');
li.setAttribute('id', ['liID' + count]);
var month = theLDate.getMonth();
var day = theLDate.getDate();
var year = theLDate.getFullYear();
var theDay = month + '/' + day + '/' + year + ' (Sunday)';
li.innerHTML = theDay;
ul.appendChild(li);
}
theLDate.setDate(theLDate.getDate() + 1);
count++;
}
But when I pick 2 dates in my calendar like so:
if I try that and say alert(theLDate.valueOf()); it returns
1309924800000
That's because that is the value of a Date object, measured in milliseconds since 1/1/1970 00:00:00, in this case corresponding to Wed Jul 6 04:00:00 2011 UTC.
Try using .toString() instead and you'll see the corresponding date in a human readable format.
The problem with your dates appearing to be in June is because the getMonth() function for odd reasons returns the month zero based, i.e. January == 0.
You need to use .innerHTML, otherwise you are not returning the text in the element.
var lDate = document.getElementById('txtLeaveDate').innerHTML;
var myDate = new Date(lDate);
document.write(myDate);
http://jsfiddle.net/jasongennaro/ua85k/
Months returned by the someDate.getMonth method are zero-indexed (from 0 to 11). So if using them to create a string add 1!
var month = theLDate.getMonth() + 1;