Cant assign value from getElementById to date? - javascript

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;

Related

Javascript while not work in Safari

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!

How to get the Week wise Start and End date in angularjs

Before I am using angularjs-DatePicker from this npm.
Here,I am able to select the date from the date picker.But now I have to fields as FromDate and ToDate which means the week StartDate and EndDate should show when any date pick in that week.
Ex: Like in Calender 01-08-2017 Start on Tue, So whenever Selects Any date from 01 to 05 then the two fields should show as FromDate as 01 and TODate as 06 and in the same whenever the user selects the 31-07-2017 the the Two fields should show as 30 and 31 of july.
I have an idea to achieve the ToDate from FromDate Calender control onchange event in DotNet as like below mentioned code
Convert.ToDouble(objstart.DayOfWeek)).ToString("dd-MM-yyyy")
But how to achieve this usecase in the angularjs.
Thanks
Ok, so what I'd do is to calculate different dates, and take the min/max depending on the start or end of the week.
Here:
//Use the date received, UTC to prevent timezone making dates shift
var pickedDate = new Date("08-03-2017UTC");
var startSunday = new Date(pickedDate);
startSunday.setDate(pickedDate.getDate() - pickedDate.getDay());
var startMonth = new Date(pickedDate);
startMonth.setDate(1);
var startDate = Math.max(startMonth,startSunday);
console.log("Start:" , new Date(startDate));
var endSaturday = new Date(pickedDate);
endSaturday.setDate(pickedDate.getDate() + (7-pickedDate.getDay()));
var endMonth = new Date(pickedDate);
endMonth.setMonth(pickedDate.getMonth()+1);//Add a month
endMonth.setDate(0);// to select last day of previous month.
var endDate = Math.min(endMonth,endSaturday);
console.log("End" , new Date(endDate));
The trick was to play with the dates, find all the possible start and end dates, then choose the right one with Math.min and Math.max which will compare the dates using their timestamp.
There is very good Library available in JavaScript to handle Date Manipulations.
https://github.com/datejs/Datejs
There is a method
Date.parse('next friday') // Returns the date of the next Friday.
Date.parse('last monday')
Using these method you can get the start and ending date of the week based on the current week.
I hope that it will help.
You can simply achieve this using the library moment. There are a lot of useful functions in this library.
var selectedDate = moment('Mon Aug 10 2017');
//If you want to get the ISO week format(Monday to Sunday)
var weekStart = selectedDate.clone().startOf('isoweek').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('isoweek').format('MMM Do');
//If you want to get the Sunday to Saturday week format
var weekStart = selectedDate.clone().startOf('week').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('week').format('MMM Do');
No need angular directive here, you could use the JavaScript extension which is below.
//get week from date
Date.prototype.getWeekNumber = function (weekstart) {
var target = new Date(this.valueOf());
// Set default for weekstart and clamp to useful range
if (weekstart === undefined) weekstart = 1;
weekstart %= 7;
// Replaced offset of (6) with (7 - weekstart)
var dayNr = (this.getDay() + 7 - weekstart) % 7;
target.setDate(target.getDate() - dayNr + 0);//0 means friday
var firstDay = target.valueOf();
target.setMonth(0, 1);
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstDay - target) / 604800000);;
};
//get date rance of week
Date.prototype.getDateRangeOfWeek = function (weekNo, weekstart) {
var d1 = this;
var firstDayOfWeek = eval(d1.getDay() - weekstart);
d1.setDate(d1.getDate() - firstDayOfWeek);
var weekNoToday = d1.getWeekNumber(weekstart);
var weeksInTheFuture = eval(weekNo - weekNoToday);
var date1 = angular.copy(d1);
date1.setDate(date1.getDate() + eval(7 * weeksInTheFuture));
if (d1.getFullYear() === date1.getFullYear()) {
d1.setDate(d1.getDate() + eval(7 * weeksInTheFuture));
}
var rangeIsFrom = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
d1.setDate(d1.getDate() + 6);
var rangeIsTo = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
return { startDate: rangeIsFrom, endDate: rangeIsTo }
};
Your code can be look like this
var startdate = '01-08-2017'
var weekList = [];
var year = startdate.getFullYear();
var onejan = new Date(year, 0, 1);//first january is the first week of the year
var weekstart = onejan.getDay();
weekNumber = startdate.getWeekNumber(weekstart);
//generate week number
var wkNumber = weekNumber;
var weekDateRange = onejan.getDateRangeOfWeek(wkNumber, weekstart);
var wk = {
value: wkNumber
, text: 'Week' + wkNumber.toString()
, weekStartDate: new Date(weekDateRange.startDate)
, weekEndDate: new Date(weekDateRange.endDate)
};
weekList.push(wk);
I guess there is no directive or filter for this, you need to create one for yourself. you can refer date object from date-time-object

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.

The day of the month does not show up properly in javascript (html)

This is my javascript code:
function borrowbook ()
{
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();
var input_day = document.getElementById("textbox").value;
var newday = today.setDate(day + input_day);
var fulltime1 = newday + "-" + month + "-" + year;
alert ("Return Date is: " + fulltime1);
}
And the result was not my expected result:
Actually what I want to do is if a user enters a value in 'Days allowed',I want to display the book return date.But I do not know why does the day of the month cannot show up properly.Any suggestion to solve this problem?
When you do:
var newday = today.setDate(day + input_day);
you are setting the value of newday to the return value of today.setDate(...), which is a time clip.
Since *input_day* is the value of a form control, and such values are always strings, the + operator will concatenate the values, not add them.
What you probably want is the date, so:
today.setDate(day + +input_day); // set the new date, converting input_date to Number
var newday = today.getDate(); // get the new date
Also, you should get the month and year after adding the day as it may change their values:
31 May + 1 day -> 1 June
There are three things you need to change.
Here is a working jsfiddle.
http://jsfiddle.net/bbankes/VMn3x/
First, the month and the year may also be incorrect. If today were 31-Dec 2014, your code would not show 10-Jan 2014, but instead 10-Dec 2013. You can rectify this by getting the day month and the year from the renew date instead of today's date.
Second, input_day is a string, so you need to parse it as an integer using the built-in javascript function parseInt();
Third, the setDate() method on a Date object does not return the new date. This is the problem that RobG shows.
The new function is as follows:
function borrowbook() {
var today = new Date();
var day = today.getDate();
var input_day = document.getElementById("textbox").value;
var returnDate = new Date();
returnDate.setDate(day + parseInt(input_day));
var returnDay = returnDate.getDate();
var returnMonth = returnDate.getMonth() + 1;
var returnYear = returnDate.getFullYear();
var fulltime1 = returnDay + "-" + returnMonth + "-" + returnYear;
alert ("Return Date is: " + fulltime1);
}

Change date format (Javascript)

I have this code:
var fd=1+self.theDate.getMonth() +'/'+ today+'/'+self.theDate.getFullYear();
It works, but it's format is Month, Day, Year.
I need to change it to: Day, Month Year.
So, I tried this:
var fd=1+today +'/'+ self.theDate.getMonth()+'/'+self.theDate.getFullYear();
Now, my change does not work. Is it that I have not done it properly or is my change right?
Thanks
I expect the correct answer is this:
var fd=today +'/'+ (self.theDate.getMonth() + 1) +'/'+self.theDate.getFullYear();
This leaves today alone, and groups Month so that it does a proper number addition instead of string concatenation.
var theDate = new Date();
var today = theDate.getDate();
var month = theDate.getMonth()+1; // js months are 0 based
var year = theDate.getFullYear();
var fd=today +'/'+ month +'/'+year
or perhaps you prefer 22/05/2011
var theDate = new Date();
var today = theDate.getDate();
if (today<10) today="0"+today;
var month = theDate.getMonth()+1; // js months are 0 based
if (month < 10) month = "0"+month;
var year = theDate.getFullYear();
var fd=""+today +"/"+ month +"/"+year
You are no longer adding 1 to the month, you are adding it to today. Make sure to parenthesize this since "x" + 1 + 2 => "x12" but "x" + (1 + 2) => "x3"

Categories