Pikaday date range don't work - javascript

I used the range function from pikaday.
with onSelectI set the date range what actually works.
Here is my example:
onSelect: function(date) {
var first_ = (date.getDate() - date.getDay())+1;
var last_ = first_ + 4;
var firstday = new Date(date.setDate(first_));
var lastday = new Date(date.setDate(last_));
picker.setStartRange(firstday);
picker.setEndRange(lastday);
picker.draw();
var f_startdate = firstday.getDate()+'.'+(firstday.getMonth()+1)+'.'+firstday.getFullYear();
var f_enddate = lastday.getDate()+'.'+(lastday.getMonth()+1)+'.'+lastday.getFullYear();
var kw = getWeekNumber(date.getFullYear()+'/'+(date.getMonth()+1)+'/'+date.getDate());
document.getElementById('calendar').value = f_startdate+' - '+f_enddate;
// document.getElementById('calendar').value = 'KW: '+(kw+1);
}
But when I select the 03.06.2016 the range is set to the "30.05.2016 - 03.05.2016" and the Input is wrong. Maybe anyone can help me.
Here is a working example: https://jsfiddle.net/24aL9f21/1/

Your issue is here:
var first_ = (date.getDate() - date.getDay())+1;
That gives you the date of the previous Monday, but also goes negative. 3 June is a Friday (day number 5), so first_ is set to:
3 - 5 + 1 = -1
Then:
var last_ = first_ + 4;
so last_ is set to 3. Now when you do:
var firstday = new Date(date.setDate(first_));
you are actually setting date to a date of -1, which is one before the start of the month so 30 May. setDate returns the time value, so firstday is a new Date instance set to 30 May also.
Then:
var lastday = new Date(date.setDate(last_));
you are setting date to 3 May (remembering that in the line above you set it to 30 May). Again, the setDate method returns the time value, so a new Date object is created for that date. So you get dates for 30 May and 3 May (and if you check date, you'll set it's also 3 May).
QED (which my Mathematics teacher told me was "Quite Easily Done"). ;-)
So your code for the Monday is fine. If you want to get the date for the following Friday, just do:
var lastday = date.setDate(date.getDate() + 4);
Here lastday and date will reference the same Date object, but creating another copy doesn't seem useful.

Related

Date calculation using javaScript

I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js

Javascript getting dates wrong dates when do .setDate(currentDate.getDate() - 30) in some cases

var fromDate = new Date();
var toDate = new Date();
fromDate.setDate(fromDate.getDate() - 1);
toDate.setDate(fromDate.getDate() - 30);
Now when i print formDate this is being printed
Date 2018-07-31T05:33:46.399Z
Now when toDate is printed this is printed
Date 2018-08-01T05:33:46.399Z
The current date is Date 2018-08-01T06:00:46.921Z
so i want to get yesturday's date and 30 days before yesturday date
How do i get previous dates without using moment
The setDate() sets the date relatively. The first snippet works as you're setting the date as 0, which will set the last date of previous month to the date object. Per the docs
If the dayValue is outside of the range of date values for the month, setDate() will update the Date object accordingly. For example, if 0 is provided for dayValue, the date will be set to the last day of the previous month.
But in the second snippet, you're setting the date as 1 (31 - 30), which won't set the date relatively, but absolutely, since 1 is a valid date, and is not outside the range. So, you end up setting the date as 1 in toDate.
The correct approach for this is to deduct 31 (assuming you want 1st July) from toDate, which creates a relative value (1 - 31 == -30), and thus, sets the date correctly.
var formDate = new Date();
var toDate = new Date();
formDate.setDate(formDate.getDate() - 1);
toDate.setDate(toDate.getDate() - 31);
console.log(formDate, toDate);
you missed 31, instead of 30
var formDate = new Date();
var toDate = new Date();
formDate.setDate(formDate.getDate() - 1);
toDate.setDate(toDate.getDate() - 31);
console.log(formDate);
console.log(toDate);

Why does adding a month to a Date object return a strange number?

The following returns 11 which is correct.
var month = d.getMonth();
alert(month);
When I try adding a month to it returns something very different
var month = d.setMonth(d.getMonth() + 1);
alert(month);
It returns: 1513230546878
Return values of methods that you are using in your code are as follows
d.getMonth() - A Number, from 0 to 11, representing the month (Link)
d.setMonth() - A Number, representing the number of milliseconds between the date object and midnight January 1 1970 (Link)
Please note, d.setMonth() will modify your Date object in place. So, if you want your code to work as expected, you can write as follows
var d = new Date()
var month = d.getMonth();
alert(month);
d.setMonth(d.getMonth() + 1);
alert(d.getMonth());
d.setMonth() method returns the updated timestamp value (See docs). That's why you got a long number.
If you want to get the month you will use as per below
var d = new Date("2017-10-03");
d.setMonth(d.getMonth() + 1);
var month = d.getMonth(); // get new month
alert(month);
hope it helps
In java script, if you write this:
var month = d.setMonth(d.getMonth() + 1);
You get a timestamp. Meaning, an integer number representing the month you chose.
This is because, setDate accepts a dayValue parameter:
Date.setDate(dayValue)
Meaning that:
var dt = new Date("Aug 28, 2008 23:30:00");
dt.setDate(24);
console.log(dt);
will result in:
Sun Aug 24 2008 23:30:00 //+ your standard gmt time
For further inquire, see this Link
//set date to now:
var d = new Date();
console.log(d);
//just checking
var month = d.getMonth();
console.log(month);
//add a month
d.setMonth(d.getMonth() + 1);
//now the month is one ahead:
console.log(d.getMonth());
console.log(d);

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

Get the number of days between 2 dates using Javascript

actually the code works fine when the date is on the same month but i had a problem when the date is on the different month like 30/09/2015 and 01/10/2015 the number of days result is 2.(sorry for my bad english)
Here's the sample code:
var dtElem1 = '30/09/2015';
var dtElem2 = '01/10/2015';
var resultElem = frm.elements['numberofdays'];
var oneDay = 24*60*60*1000;
var x = dtElem1.value;
var y = dtElem2.value;
var arr1 = x.split('/');
var arr2 = y.split('/');
var dt1 = new Date();
dt1.setFullYear(arr1[2], arr1[1], arr1[0]);
var dt2 = new Date();
dt2.setFullYear(arr2[2], arr2[1], arr2[0]);
resultElem.value = Math.round(Math.abs((dt1.getTime() -
dt2.getTime())/(oneDay)));
The Date methods count months from zero, so you should substract 1 from the month number when setting the date. That explains your bug, since you end up substracting the 30th of october from the 1st of november and october has 31 days.
This will give the expected result:
dt1.setFullYear(arr1[2], arr1[1] - 1, arr1[0])
dt2.setFullYear(arr2[2], arr2[1] - 1, arr2[0])
Note that you don't need to create the Date and then set it. You can pass the same arguments directly to the constructor:
dt1 = new Date(arr1[2], arr1[1] - 1, arr1[0])
dt2 = new Date(arr2[2], arr2[1] - 1, arr2[0])

Categories