Problem with getDay() method javascript - javascript

I'm trying to get the day name in javascript.
Every time I search for usage of the function getDay(), it is explained that this method returns the day of the week, for example: 0 is sunday, 1 is monday etc.
So the 1st janauary 2010 was a friday, can someone explain why i'm getting 1 instead of 5? The same for 2nd janauary 2010, i'm getting 2 instead of 5.
I've tried some ways to do that without success.
Here's my code :
theDay = new Date(2010,01,01);
alert(theDay.getDay());
Thank You !!!

The month in JS is zero-based, just like the day of the week.
Date(2010,01,01) is 1 February, 2010. January is month zero. Sure enough, 1 February 2010 was a Monday (I remember it well).
Try this:
var theDay = new Date(2010,00,01);
alert(theDay.getDay());

The month starts at 0, so what you're doing is trying to find Feb 1st, 2010 which is a Monday. This would be correct:
theDay = new Date(2010,0,01);
alert(theDay.getDay());

Related

Moment.js incorrect date for week number

This should return the last week of the year:
moment().year('2021').week(51).day('monday').format('YYYY-MM-DD');
But instead it is returning 2022-12-12. I think there is a bug in moment.js.
Here is codepen: https://jsfiddle.net/5402bkmp/
You should post your code here, not elsewhere.
var now = moment().year('2021').week(51).day('monday').format('YYYY-MM-DD');
console.log(now.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Breaking down the code, if run on Monday 27 December:
moment()
Creates a moment object for 27 Dec 2021
.year('2021')
Sets the year to 2021, which changes nothing because it's already set to 2021. It also handles cases like 2020-02-29 + 1 year, which becomes 2021-02-28.
.week(51)
Sets to "localised" start of week 51. The problem is, how does the user know how moment.js localises things? For me it seems to be Sun 12 Dec 2021. That numbering seems to be based on the first week starting on the first Sunday on or before 1 Jan 2021 (i.e. Sun 27 Dec 2020), e.g. new Date(2020, 11, 27 + 50*7) gives 12 Dec 2021.
.day('monday')
Sets the date to Monday of the same localised week, again it's hard for users to know what their "localised" week is. For me, it just keeps it as Monday because it seems the localised week starts on Sunday (my PC is set to start weeks on Monday).
.format('YYYY-MM-DD')
So I think it's clear that a problem with using the week method is that neither the programmer nor user know what the result will be because they don't know what moment.js is using to localise things (possibly navigator.language). And results can be very different to what is expected.
One fix, as Sergiu suggested, is to use isoWeek so at least the result is consistent and predictable. ISO weeks start on Monday, with the first week being the one with the most days in the subject year. It's also expressed as the week of the first Thursday, or the week of 4 January, they all work to give the same Monday as the start of week 1 of any particular year. Some years have 52 weeks, some 53, and usually a couple of days near the end of the year are part the first week of the following year or last week of the previous year.
You might also like to see Get week of year in JavaScript like in PHP.
You need to use .isoWeek instead of .week (documented here, though it's unclear to me why).
That's works really good to me!
moment.locale("myLanguage", { week: { dow: 0 }});
momentExt.updateLocale("myLanguage", { week: { dow: 0 }});
Example here: https://jsfiddle.net/naqr7upL/

Will assigning 0 to the 3rd parameter of a JavaScript Date() object always create an end of month date?

I'm working on a jQuery credit card expiration date validation script. Credit cards expire after the last day of the expiration month. For instance, if the card expires on 8/2013 then it's good through 8/31/2013.
In the past on the server side I've determined the last day of the month by adding 1 to the current month, then subtracting 1 day.
Today I noticed that when creating a new date, if 0 is applied to the 3rd parameter of the JavaScript Date() object, the resulting date will be the end-of-month day. But I've been unable to locate any online documentation to affirm this observation.
Here is some sample code.
var month = 10;
var year = 2013;
var expires = new Date(year, month, 0);
alert(expires);
And here is a jsFiddle example that I created.
This is a bit confusing, because I thought in JavaScript months were zero based. I've tested this in Chrome, Firefox, IE, and Safari, and the behavior appears consistent. The returned date consistently displays the last day of the month. This looks like a lucky find, but I'd really like to understand what is happening here.
Am I safe to run with this approach to assigning an end of month date, and if so is there some online documentation that I can point to which affirms this? Thanks.
Months are zero-based. That creates an end-of-month date in the previous month. Month 10 is November, so creating a date with day 0 in November gives you the end of October (month 9).
That is, day 0 in November means "the day before 1 November", which is the last day of October. Day -1 in November would be 30 October.

JavaScript: Convert Day/Week Into Year

I have been using Stack Overflow for a number of months now, but this is my first post.
I require a function to convert a week number and and day of week into a dd/mm/yyyy format.
The date values i have to work with are in the format day/weekNumber. So for example: 3/43 converts to Wednesday 24 October 20XX. The year value will be the current year.
The day value starts at 1 (Monday).
I have found lots of functions on the internet (such as this, this and this). Some work with ISO 8601 dates, which i do not think will work for me. And i have not yet found one that works for me.
Thanks in advance,
This solution does require an extra library to be added, but I think it is really worth it. It is a momentjs library for manipulating dates and time. It is actively maintained and has a great documentation. Once you get the values for day and weekNumber (in our case 3 and 43), you should do as follows:
function formatInput(day, weekNumber){
var currentDate = moment(new Date()); // initialize moment to a current date
currentDate.startOf('year'); // set to Jan 1 12:00:00.000 pm this year
currentDate.add('w',weekNumber - 1); // add number of weeks to the beginning of the year (-1 because we are now at the 1st week)
currentDate.day(day); // set the day to the specified day, Monday being 1, Sunday 7
alert(currentDate.format("dddd, MMMM Do YYYY")); // return the formatted date string
return currentDate.format("dddd, MMMM Do YYYY");
}
I think this library might be useful to you later on and there are plenty of possibilities regarding date and time manipulation, as well as formatting options. There is also a great documentation written for momentjs.
So assuming you have the values of 3 and 43 separately, you can just do some simple maths on the first day of the current year:
Get 1st January Current Year
Add (43 * 7 + 3)
Something like this maybe:
var currentDate = new Date();
var startOfYear = new Date(currentDate.getFullYear(), 0, 1);//note: months start at 0
var daysToAdd = (43 * 7) + 3;
//add days
startOfYear.setDate(startOfYear.getDate() + daysToAdd);
Here is an example
EDIT
On second thoughts, I think I was wrong with your requirements. It seems you require a specific day of the week. Check this out for a better solution.
The problem is that it all depends on your definition of a week. This year starts on a sunday, so does that mean that 02/01/2012 (the first monday of this year) is the start of the second week?
My latest example will first find the start of the specified week, and then find the next occurrence of the specified day
According to ISO when dealing with week dates, the week starts on Monday and the first week of the year is the one that contains the first Thursday of the year. So for 2012, the first week started on Monday, 2 January and the first week of 2013 will start on Monday, 31 December 2012.
So if 3/43 is the third day of the 43rd week (which is the ISO date 2012-W43-3), then it can be converted it to a date object using:
function customWeekDateToDate(s) {
var d, n;
var bits = s.split('/');
// Calculate Monday of first week of year this year
d = new Date();
d = new Date(d.getFullYear(),0,1); // 1 jan this year
n = d.getDay();
d.setDate(d.getDate() + (-1 * n +( n<5? 1 : 8)));
// Add days
d.setDate(d.getDate() + --bits[0] + --bits[1] * 7);
return d;
}
console.log(customWeekDateToDate('3/43')); // 01 2012-10-24
Note that this uses dates, otherwise daylight saving changeovers may result in the wrong date.

JS date() returning incorrect date

I'm am trying to format a date in Javascript but the date command is returning the wrong date unless I use toUTCString() which returns the correct date, I've tried different ways of giving the date to the Date() function and both get and getUTC functions to get the date. I've also tried on different browsers (Chrome, Safari, FireFox) and what makes in even more confusing is if I do it in Chrome's inspector is works perfectly. And I missing something obvious?
var d = new Date(1324141200000);
// return "Sat, 17 Dec 2011 17:00:00 GMT" - Correct!
alert(d.toUTCString());
// returns "6-11-2011" - Wrong!
alert(d.getUTCDay() +'-'+ d.getUTCMonth() +'-'+ d.getUTCFullYear());
The "getUTCDay()" function returns the day of the week. The months are numbered from zero. Saturday is the sixth day of the week (in JavaScript land at least), and 11 is the 12th month counting from zero.
Thus, all is well.
The day of the month can be retrieved with "d.getUTCDate()".
d.getUTCDay() // day of week
d.getUTCMonth() // zero based index
Instead of getUTCDay, you want getUTCDate. And getUTCMonth returns 0-11 (0 = January). Section 15.9.1 of the specification may help, but the language is heavy-going.
Use
getFullYear()
function to get the year,
getMonth()
function to get the month, and
getDate()
function to get the day.

Calculating Date in JavaScript

I am currently looking to calculate a custom date in JavaScript and my head is beginning to hurt thinking about it. I have a countdown clock that is to start every other Tuesday at 12pm. I have the countdown function working properly using the jQuery countdown plugin by Keith Wood but need assistance in calculating every other Tuesday of the month and having it reset on this day.
All help is greatly appreciated as always.
Thansk in advance
I've had to do something similar (not in JS but the algorithm is similar enough)
Now, before i start, to clarify i'm assuming this is something that happens fortnightly regardless of the length of the month, and not on the second and 4th Tuesday regardless of when it last happened, which is simpler to solve
Pick a date in the past that this event has occured on (or the date of the first occurrence) , we'll call this date base in the following code
var base=new Date('date of first occurrence');
var one_day=1000*60*60*24; //length of day in ms
// assume we care about if the countdown should start today
// this may be different if you are building a calendar etc.
var date_to_check=new Date();
var diff_in_days=math.floor(date_to_check-base)/one_day);
var days_since_last_reset= diff_in_days%14;
if(days_since_last_reset == 0){
//date_to_check is the same day in the fortnightly cycle as base
//i.e. today at some point is when you'll want to show the timer
//If you only want to show the timer between certain times,
//add another check here
}else{
//next reset in (14 - days_since_last_reset) days from date_to_check
}
Or the code-golf-esque version:
if( Math.floor((new Date()-new Date('date of first occurrence'))/1000/60/60/24)%14 == 0 )
//reset/start timer
Please find attached link for Date Library to get the custom calculation date and time functions.
To use it client side, download index.js and assertHelper.js and include that in your HTML.
<script src="assertHelper.js"></script>
<script type="text/javascript" src="index.js"></script>
$( document ).ready(function() {
DateLibrary.getDayOfWeek(new Date("2015-06-15"),{operationType:"Day_of_Week"}); // Output : Monday
}
You can use different functions as given in examples to get custom dates.
To get First Day of quarter From Given Date
DateLibrary.getRelativeDate(new Date("2015-06-15"),
{operationType:"First_Date",granularityType:"Quarters"}) // Output : Wed Apr 01 2015 00:00:00
If first day of week is Sunday, what date will be on Wednesday, if
given date is 15th June 2015
DateLibrary.getRelativeDate(iDate,
{operationType: "Date_of_Weekday_in_Week",
startDayOfWeek:"Sunday",returnDayOfWeek:"Wednesday"}) // Output : Wed Jun 17 2015 00:00:00
If first day of week is Friday, what date will be on Tuesday of 3rd
Week of 2nd month of 3rd quarter of year containing 15th June 2015 as
one of the date.
DateLibrary.getRelativeDate(new Date("2015-06-15"),
{operationType: "Date_of_Weekday_in_Year_for_Given_Quarter_and_Month_and_Week",
startDayOfWeek:"Friday",returnDayOfWeek:"Tuesday", QuarterOfYear:3, MonthOfQuarter:2, WeekOfMonth:3}) // Output : 18th Aug 2015
If first day of week is Tuesday, what week number in year will be
follow in 15th June 2015 as one of the date.
DateLibrary.getWeekNumber(new Date("2015-06-15"),
{operationType:"Week_of_Year",
startDayOfWeek:"Tuesday"}) // Output : 24
There are Date Difference functions also available
DateLibrary.getDateDifference(new Date("2016-04-01"),new Date("2016-04-16"),
{granularityType: "days"}) //output 15
Function for Convert number to Timestr
DateLibrary.getNumberToTimeStr("345", {delimiter: ":"}) //output 00:03:45
It also supports Julian date conversion
DateLibrary.julianToDate("102536") //output Fri Jun 20 2003 00:00:00
There is a JavaScript implementation of RFC 2445 recurrence rules : http://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/demos/calendar/rrule-cajita.js which requires some files in the same directory. See the unit test ( http://code.google.com/p/google-caja/source/browse/trunk/tests/com/google/caja/demos/calendar/rrule_test.js ) for examples of how it works.
Try using it to parse RRULE:FREQ=WEEKLY;BYDAY=TU;INTERVAL=2 which means every second (because of the interval) week (because of the frequency) on Tuesday (because of the byday).
Have a look at the date.js library. It has several date parsing helpers including Date.today().next().tuesday() (among others).

Categories

Resources