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.
Related
I'm trying to increment one day to a given date. My code, inspired by this answer, looks like:
var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(date.getDate() + 1);
However, I'm seeing a strange behaviour. Today is December 5th, 2019. If the user selects January 1, 2020 (stored in date variable), then backupDate ends up being January 2nd, 2019, instead of 2020. What is wrong with this code? How should I go about incrementing the date, if what I'm doing is wrong?
Note: because of whatever policies my company has, I can't use any JavaScript library other than jQuery.
new Date() returns the current Date(example: 05/12/2019). You are just changing the date alone in current date. Still the year is 2019.
it should be like,
date.setDate(date.getDate() + 1);
if you can't change the original date object, then it can be done like this,
var changedDate = new Date(date);
changedDate.setDate(changedDate.getDate() + 1);
var date = getDateFromUIControl();
var backupDate = new Date();
backupDate.setDate(new Date(date).getDate() + 1);
nextDay is one day after date:
var date = getDateFromUIControl();
var nextDay = new Date(date.getYear(), date.getMonth(), date.getDate()+1);
Also you don't need to worry about overflowing d.getDate()+1 (e.g. 31+1) - the Date constructor is smart enough to go into the next month.
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);
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")
How can I convert a string representation of a date to a real javascript date object?
the date has the following format
E MMM dd HH:mm:ss Z yyyy
e.g.
Sat Jun 30 00:00:00 CEST 2012
Thanks in advance
EDIT:
My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)
Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.
A simple solution thus might be :
var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);
If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :
var replacements = {
"ACDT": "+1030",
"CEST": "+0200",
...
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);
This might be a good list of time zone abbreviation.
You can use following code to convert string into datetime:
var sDate = "01/09/2013 01:10:59";
var dateArray = sDate.split('/');
var day = dateArray[1];
// Attention! JavaScript consider months in the range 0 - 11
var month = dateArray[0] - 1;
var year = dateArray[2].split(' ')[0];
var hour = (dateArray[2].split(' ')[1]).split(':')[0];
var minute = (dateArray[2].split(' ')[1]).split(':')[1];
var objDt = new Date(year, month, day, hour, minute);
alert(objDt);
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.