I have the following code, which returns the number of days in a month:
daysInMonth(month:number, year:number) {
return new Date(year, month, 0).getDate();
}
Let's say this gives me 31. Now, in my html, I want to create a dropdown element with all the days in the month, listed out in order. So, my dropdown would consist of:
1,2,3,4,5,6,7,8,9,10,11..... All the way to 31.
I need to build this object dynamically since the days in the month will change based on the month.
What's the most efficient way to do that?
I would use jQuery.
So somewhere along the line you'd do something:
var dropDown = $('<select/>').appendTo('body');
for (var i = 1; i <= daysOfMonth; i++) {
dropDown.append('<option value=' + i + '>' + i + '</option>');
}
You would clearly need to get the value of daysOfMonth from somewhere previously.
You can use the following to achieve the dropdown:
(function() {
var totalDays = daysInMonth(2, 2014),
selectEl = document.createElement('select');
for (var i = 1; i <= totalDays; i++) {
var option = document.createElement('option');
option.appendChild(document.createTextNode(i));
option.setAttribute('value', i);
selectEl.appendChild(option);
}
document.body.appendChild(selectEl);
}());
DEMO
Related
Image of my array valuesI have a function to "Wed 12/8" and "Wed 12/8". However, when I use them in this function they are not equal for some reason yet they are identical. The function does not append and acts as if they are completely different.
function filterDate() {
for (var i = 0; i < dateList.length; i++) {
if(dateList[i] == today) {
appendItem(filteredDate, dateList[i]);
appendItem(filteredID, stateID[i]);
appendItem(filteredCase, totalCases[i]);
appendItem(filteredState, usState[i]);
}
}
}
Here the get date code.
//Date
var now = new Date();
//Gets the current days date
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var months = ['1','2','3','4','5','6','7','8','9','10','11','12'];
var weekday = days[now.getDay() - 1];
var day = now.getDate() - 1;
var month = months[now.getMonth()];
var today = weekday + " " + month + "/" + day;
//Console logs todays date
console.log(today);
The values are the exact same but the computer thinks they are not. When I manually change today to "Wed 12/8" it works but the variable seems to mess it up though I may be wrong. What's happening and how do I fix this as it is crucial to my program?
The problem should be the way you populate the dateList array. Are you sure it gets filled with strings too, and not for example date objects? The code you provided does not show anything related to that array.
Edit:
Based on the image you provided later, I think the issue will be that your strings in the array contain quotation marks.
Remove them from the strings. (For example by slicing the first and last characters from it in the filterDate function)
function filterDate() {
for (var i = 0; i < dateList.length; i++) {
if(dateList[i].slice(1,-1) == today) {
appendItem(filteredDate, dateList[i]);
appendItem(filteredID, stateID[i]);
appendItem(filteredCase, totalCases[i]);
appendItem(filteredState, usState[i]);
}
}
}
I'm trying to create calendar and I tried below.
function displayCalendar() {
var dateNow = new Date();
var month = dateNow.getMonth();
var counter = 1;
var nextMonth = month + 1;
var prevMonth = month -1;
var day = dateNow.getDate();
var year = dateNow.getFullYear();
var dayPerMonth = ["31","28","31","30","31","30","31","31","30","31","30","31"]
// days in previous month and next one , and day of week.
var nextDate = new Date(nextMonth +' 1 ,'+year);
var weekdays = nextDate.getDay();
var numOfDays = dayPerMonth[month];
var ul = document.getElementById('dates');
var monthInt = month + 1;
var currentMonth = document.getElementById('currentMonth');
monthInt.toString().length === 1 ? currentMonth.innerHTML = "0" + monthInt : currentMonth.innerHTML = monthInt;
// add empty li
while (weekdays > 0) {
var li = document.createElement('li');
ul.appendChild(li);
weekdays--;
}
while (counter <= numOfDays) {
var li = document.createElement('li');
li.innerHTML = counter;
ul.appendChild(li);
counter++;
}
}
It works fine but when I change month to August like this
var month = dateNow.getMonth() + 1;
first date starts at Sunday. It should start at Wednesday.
I think this code is not working
while (weekdays > 0) {
var li = document.createElement('li');
ul.appendChild(li);
weekdays--;
}
In chrome it works and starts at Wednesday correctly.
Anyone know why it's not working?
Thank you in advance!
I think the problem is your date format. Chrome is being more generous in parsing the date you're giving it, which is a string that looks like "7 1,2018". Chrome accepts that as a valid date, Safari doesn't. If you made sure you put slashes between the month, date, and year, like "7/1/2018" it would work better.
I think the problem is that in calculating nextMonth to put in your string you are assuming months in dates in js start with 1. But they start with 0. So your date now get month is giving you 6, not 7, and when you add 1 you are getting 7, not 8. Add 2 and you will get Wednesday like you want.
Specifically you need var nextMonth = month + 2;
I tested this in Firefox. I agree with the other posted answer about not loving the date format.
Also, you appear not to use prevMonth. You should remove it. Or if it you need for something, it should not have the -1.
Finally, you are going to want to revisit your index into the daysPerMonth array. If you want the number of days in next month, it is off.
As kshetline said, the problem was date format.
Changed this code
var nextDate = new Date(nextMonth +' 1 ,'+year);
var weekdays = nextDate.getDay();
to
var nextDate = new Date(year, month, 1);
var weekdays = nextDate.getDay();
then it worked fine!
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.
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
I am trying to write a select drop down which is dynamically filled up with options, the options are the years, e.g. 2010, 2011, 2012
But with each coming year the webpage should add new entry in the drop down with the current year. The first entry of the year is 2010 fixed but the last entry is dynamic and depends on the current year..
Any help?
Something like this?
var currentYear = new Date().getFullYear();
for (var i = 2010; i <= currentYear; i++) {
var selected = '';
if (i == currentYear)
selected = 'selected';
$("#years").append("<option value='" + i + "'" + selected + ">" + i + "</option>")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='years' />
This is one way of doing it .. fiddle
$("select").append("<option value='added'>added</option>");
append option according to your logic.
Here is the jsfiddle link (without jquery).
<form>
<select id="mySelect">
</select>
</form>
Javascript:
var x = document.getElementById("mySelect");
var to = new Date().getFullYear();
var option;
for (var i = 2010; i <= to; i++)
{
option = document.createElement("option");
option.text = i;
x.add(option);
}
Just use the actual date :
var startYear = 1950;
var currentYear = new Date().getFullYear();
And then you can generate your select options
var select = '<select>';
for (var i = startYear; i <= currentYear; i++){
select += '<option>'+i+'</option>';
}
select += </select>;
var date = new Date();
var year = date.getFullYear();
for (var i=2010;i<year+1;i++) {
$('#MySelect').append('<option value="'+i+'">'+i+'</option>')
}
FiDDLE
Why don't you select the current year substract 2010 from it ( because it is a fix end) and then you will count up from 2010 adding the amount from your result?
Thats how I would do that with the first thoughts.
Edit:
If you fill the dropdown on each load of the page you always fill that array with the amount calculated from your substraction.
I don't get the problem.