I will provide two dates, as a range e.g 5th Oct 2016 to 5th December 2016, And 5th Oct was Wednesday so return me all the Wednesdays till 5th December 2016.
How can this be possible using Javascript or AngularJS ?
Though not completely sure what you want to do, I think this will give you enough to work with:
var startdate = new Date("2016-10-05");
var enddate = new Date("2016-12-05");
var wednesdays = [];
while (startdate <= enddate) {
wednesdays.push(startdate);
// add a week
startdate = new Date(startdate.setDate(startdate.getDate() + 7));
}
console.log(wednesdays);
Related
I need to get "previous August, 1" date using moment.js; as there's no "previous" method in it, how to do this?
As far as I know there's nothing in the moment api for this (yet). There was some chatter about doing something similar on a GitHub issue a while back.
So you'll probably need to do it yourself.
Last August is either this year, if it's after August or last year if it's before. You can simply test this and act accordingly. So last August is 2017:
let aug = moment("08-01", "MM-DD")
let lastAug = aug < moment() ? aug : aug.subtract(1, 'years')
console.log("Last August: ", lastAug.format("dddd DD-MM-YYYY"))
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
Last February, however, is 2018.
let feb = moment("02-01", "MM-DD")
let lastfeb = feb < moment() ? feb : feb.subtract(1, 'years')
console.log("Last February: ", lastfeb.format("dddd DD-MM-YYYY"))
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
you can use subtract() method of momentjs
var now = moment().format("dddd DD-MM-YYYY");
var previous = moment().subtract(1, 'years').format("dddd DD-MM-YYYY");
document.write(now+"<br/>"+previous);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
The code below will find the first august this year. If the day has not occured yet, then it will return the first august of the previous year.
var thisYear = (new Date()).getFullYear();
var lastAugust = new Date("8/1/" + thisYear);
if(moment() < lastAugust)
lastAugust = new Date("8/1/" + (thisYear - 1));
var result = moment(lastAugust.valueOf()).format("dddd DD-MM-YYYY");
document.write(result);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script>
I get wrong output for months that have 29,30,31th. Please help thanks.
//EFFDATE = 29/03/2017;
EFFDATE = document.mainform2.EFFDATE.value;
var dayOfDate = parseFloat(EFFDATE.substring(0,2));
var monthOfDate = parseFloat(EFFDATE.substring(3,5));
var yearOfDate = parseFloat(EFFDATE.substring(6,10));
var date1 = new Date;
var date2 = new Date;
date1.setDate(dayOfDate);
date1.setMonth(monthOfDate -1);
date1.setFullYear(yearOfDate);
console.log(date1);
For example i pick the 29th of March, the system output for date1 is friday march 01 2017.
i pick 30th of March it show friday march 02 2017
It is important to maintain a certain order when you are manipulating dates. Calling new Date will return a date object with the month February. But when you set the day to 29 using setDate, JavaScript will change the date to March, 01 as there is no February, 29 in 2017.
So you either have to set the month first, then the day. Or just use this code:
var EFFDATE = 29/03/2017;
new Date(EFFDATE.split('/').reverse().join('-'));
The setMonth method has an optional second parameter for the day of the month. If it's absent, getDate() is used, and the date is still incomplete.
So this should solve the issue:
date1.setMonth(monthOfDate-1, dayOfDate);
date1.setFullYear(yearOfDate);
Wrong but I'll leave it here for posterity
The second parameter to substring should be the number of characters you want not the index.
If you debugged this and looked at the value of EFFDATE.substring(3,5) you'd see 03/20 not 03 as you were probably thinking.
var dayOfDate = parseFloat(EFFDATE.substring(0,2));
var monthOfDate = parseFloat(EFFDATE.substring(3,5));
var yearOfDate = parseFloat(EFFDATE.substring(6,10));
should be:
var dayOfDate = parseFloat(EFFDATE.substring(0,2));
var monthOfDate = parseFloat(EFFDATE.substring(3,2));
var yearOfDate = parseFloat(EFFDATE.substring(6,4));
UPDATE
I was thinking of substr rather than `substring which is subtley different.
In this sample code to convert a string to a date:
function stringToDate(){
var edate = "2015-06-01";
Logger.log(edate);
var input = edate.split('-');
var date = new Date();
date.setUTCFullYear(input[0],input[1] - 1,input[2]);
Logger.log(date);
}
Logging the date returns "Mon Jun 01 20:07:45 GMT+01:00 2015", which is correct, as the month '06' - 1 = 5 corresponds to the month of June for the this.
However, this almost identical function:
function stringToDate2(){
var edate = "2015-06-01";
Logger.log(edate);
var input = edate.split('-');
var date = new Date();
date.setUTCFullYear(input[0]);
date.setUTCMonth(input[1] - 1);
date.setUTCDate(input[2]);
Logger.log(date);
}
Returns "Wed Jul 01 20:10:04 GMT+01:00 2015". Some other values return equally screwy results. Why do I get a different result for 'setUTCMonth' then for 'setUTCFullYear'?
Set the Date before the Month
date.setUTCFullYear(input[0]);
date.setUTCDate(input[2]);
date.setUTCMonth(input[1] - 1);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setUTCMonth
If a parameter you specify is outside of the expected range,
setUTCMonth() attempts to update the date information in the Date
object accordingly. For example, if you use 15 for monthValue, the
year will be incremented by 1, and 3 will be used for month.
Each of the UTC functions has a similar note about out of range values.
So because of this:
new Date() gets the current date, and thus today being 5/31 the date is 31.
There are some months without a 31st date, so 31 is outside the range for date so it is updated accordingly.
So if you try to set the month for say February without changing the date first,
The date would be 2/31/2015, but February only has 28 days this year so it rolls over to 3/03/2015
And in your case, if you try to set it for June, 6/31/2015, June never has a 31st date so again it rolls over to 7/01/2015. And so on.
So change the date first like I show above or set a default date when you create it:
new Date("01/01/2015")
I'm using this script located here: http://www.javascriptkit.com/script/script2/dyndateselector.shtml
If you try it, and go to any of April, June, September or November, you will notice that the day of the week columns are incorrect. Here's a list of incorrect data (the x starts y stuff is showing the following month.)
Bugged months:
4/April (starts Sunday instead of Friday)
May starts Sunday
6/June (starts Friday instead of Wednesday)
July starts Friday
9/September (starts Saturday instead of Thursday)
October starts Saturday
11/November (starts Thursday instead of Tuesday)
December starts Thursday
You'll notice that every bugged month is starting with the day of the following month, yet all the other months seem to be correct.
I can't find anything on this problem. Anyone able to help? The actual Javascript alone can be found here, and the getDay() method occurs on line 125: http://pastebin.com/0zuBYrzv
I've tested in both Firefox and Chrome.
Here's some very simple code to demonstrate the issue:
<script>
var d = new Date();
d.setMonth(5);
d.setFullYear(2011);
d.setDate(1);
alert(d.getDay());
</script>
This will create an alert with the message "5", meaning Friday (5+1 = 6, Friday is the 6th day of the week,) when in fact Wednesday is the start of the week.
This is actually pretty interesting as i am guessing that tomorrow your original code will work as you want again.
What i think is happening is you are creating a new Date and that will automaticly initialize to today (31th of may).
Then you set the Month to June by which you basically say make it 31th of June. This date doesn't exist so javascript will turn it into 1th of July.
Finally you set the Date but since your month is not anymore what you want it to be the results will be wrong.
Looks like 0 is january and 11 is december.
Apparently JavaScript doesn't like it if I set the month, full year, then day. What I must do is set them all in one function, like so:
<script>
var d = new Date();
d.setFullYear(2011, 5, 1);
alert(d.getDay());
</script>
I think this is a bug in Javascript's Date Object.
Please take a look at the following code.
(I'm using w3school's JSref tool online to see it quickly.)
Please note, the ways used below are told by w3 schools themselves.
Some examples of instantiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24) (//THIS IS WRONG - unexpected results!!!)
var d3 = new Date(79,5,24,11,33,0)
So please be careful when using this Date object, looks like certain ways of instantiating dates are better than others.
<script type="text/javascript">
function whatDayIsToday(date)
{
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
document.write("Today is " + weekday[date.getDay()] + ", <br />");
document.write("the " + date.getDay() + getSuffix(date.getDay()) + " day of the week. <br /><br />")
}
function getSuffix(num)
{
return (num>3)?"th":(num==3)?"rd":(num==2)?"nd":(num==1)?"st":"";
}
//CORRECT
var d3 = new Date("01/01/2011");
whatDayIsToday(d3);
//CORRECT
var d2 = new Date("01/01/2011");
whatDayIsToday(d2);
//DOESN'T WORK
var d5 = new Date("1-1-2011");
whatDayIsToday(d5);
//WRONG
var d4 = new Date("2011", "01", "01");
whatDayIsToday(d4);
//DAY OF WEEK IS WRONG
var d = new Date(2011, 1, 1);
whatDayIsToday(d);
//DAY OF WEEK IS ALSO WRONG
var d0 = new Date(11, 1, 1);
whatDayIsToday(d0);
</script>
outputs (all using some format of 1/1/2011) are:
Today is Saturday,
the 6th day of the week. (CORRECT, January first this year was a saturday)
Today is Saturday,
the 6nd day of the week. (CORRECT)
Today is undefined,
the NaNnd day of the week. (WRONG FORMATTING, DOESN'T WORK - EXPECTED)
Today is Tuesday,
the 2nd day of the week. (WRONG - UNEXPECTED)
Today is Tuesday,
the 2nd day of the week. (WRONG - UNEXPECTED)
Today is Wednesday,
the 3nd day of the week. (WRONG - UNEXPECTED)
Based on the other answers to this question, I'm guessing it has to do with the day I'm on currently (8/26/2011) - this would be my starting new Date() and the days and/or years getting applied in the wrong order.
However, it sure would be nice if this thing worked!
This is the typical wrong approach:
var days = ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"];
var d = new Date();
d.setFullYear(selectYear.options[selectYear.selectedIndex].value);
d.setMonth(selectMonth.options[selectMonth.selectedIndex].value-1);
d.setDate(selectDay.options[selectDay.selectedIndex].value);
alert(days[d.getDay()]);
It will work most of the time. But it will have problems with when current date is 31 and when trying to set date to 31 for when set at a month with less than 31 days.
This is a good way:
var days = ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"];
var d = new Date(0); // solves all problems for existing dates
d.setFullYear(selectYear.options[selectYear.selectedIndex].value);
d.setMonth(selectMonth.options[selectMonth.selectedIndex].value-1);
d.setDate(selectDay.options[selectDay.selectedIndex].value);
if( d.getDate() == selectDay.options[selectDay.selectedIndex].value ) {
alert(days[d.getDay()]);
}
else {
alert("this date doesn't exist"); // date was changed cuz date didn't exist
}
Constructing the date with new Date(0) sets the date to 1 jan, this is good because the date is not 31st and january has 31 days which give us the space we need. It wont fail on the 31st and we don't need to set the datas in any special order. It will always works.
If the user sets month to september (30 days) and date to 31 the data object will hold either 1 oct or 1 sep (depending on which order you set them in). Which is irrelevant because they are both wrong. A simple check if the date is what we set it to will tell us if the date is a existing date, if not we can tell the user this.
How can I create a date object which is less than n number of months from another date object? I am looking for something like DateAdd().
Example:
var objCurrentDate = new Date();
Now using objCurrentDate, how can I create a Date object having a date which is six months older than today's date / objCurrentDate?
You can implement very easily an "addMonths" function:
function addMonths(date, months) {
date.setMonth(date.getMonth() + months);
return date;
}
addMonths(new Date(), -6); // six months before now
// Thu Apr 30 2009 01:22:46 GMT-0600
addMonths(new Date(), -12); // a year before now
// Thu Oct 30 2008 01:20:22 GMT-0600
EDIT: As reported by #Brien, there were several problems with the above approach. It wasn't handling correctly the dates where, for example, the original day in the input date is higher than the number of days in the target month.
Another thing I disliked is that the function was mutating the input Date object.
Here's a better implementation handling the edge cases of the end of months and this one doesn't cause any side-effects in the input date supplied:
const getDaysInMonth = (year, month) => new Date(year, month, 0).getDate()
const addMonths = (input, months) => {
const date = new Date(input)
date.setDate(1)
date.setMonth(date.getMonth() + months)
date.setDate(Math.min(input.getDate(), getDaysInMonth(date.getFullYear(), date.getMonth()+1)))
return date
}
console.log(addMonths(new Date('2020-01-31T00:00:00'), -6))
// "2019-07-31T06:00:00.000Z"
console.log(addMonths(new Date('2020-01-31T00:00:00'), 1))
// "2020-02-29T06:00:00.000Z"
console.log(addMonths(new Date('2020-05-31T00:00:00'), -6))
// "2019-11-30T06:00:00.000Z"
console.log(addMonths(new Date('2020-02-29T00:00:00'), -12))
// "2019-02-28T06:00:00.000Z"
Create date object and pass the value of n, where n is number(add/sub) of month.
var dateObj = new Date();
var requiredDate= dateObj.setMonth(dateObj.getMonth() - n);
var oldDate:Date = new Date();
/*
Check and adjust the date -
At the least, make sure that the getDate() returns a
valid date for the calculated month and year.
If it's not valid, change the date as per your needs.
You might want to reset it to 1st day of the month/last day of the month
or change the month and set it to 1st day of next month or whatever.
*/
if(oldDate.getMonth() < n)
oldDate.setFullYear(oldDate.getFullYear() - 1);
oldDate.setMonth((oldDate.getMonth() + n) % 12);
You have to be careful because dates have a lot of edge cases. For example, merely changing the month back by 6 doesn't account for the differing number of days in each month. For example, if you run a function like:
function addMonths(date, months) {
date.setMonth((date.getMonth() + months) % 12);
return date;
}
addMonths(new Date(2020, 7, 31), -6); //months are 0 based so 7 = August
The resulting date to return would be February 31st, 2020. You need to account for differences in the number of days in a month. Other answers have suggested this in various ways, by moving it to the first of the month, or the last of the month, or the first of the next month, etc. Another way to handle it is to keep the date if it is valid, or to move it to the end of the month if it overflows the month's regular dates. You could write this like:
function addMonths(date, months) {
var month = (date.getMonth() + months) % 12;
//create a new Date object that gets the last day of the desired month
var last = new Date(date.getFullYear(), month + 1, 0);
//compare dates and set appropriately
if (date.getDate() <= last.getDate()) {
date.setMonth(month);
}
else {
date.setMonth(month, last.getDate());
}
return date;
}
This at least ensures that the selected day won't "overflow" the month that it is being moved to. Finding the last day of the month with the datePart = 0 method is documented here.
This function still leaves a lot to be desired, as it doesn't add years and you can't subtract more than a year (or you will run into a new issue with negatives being involved). However, fixing those and the other issues you may run into (namely timezones) will be left as an exercise for the reader.