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.
Related
If I have a date of May 31, 2014, then if I say date.setMonth(date.getMonth() + 1) to get to the next month, I get July 01, 2014. I would expect to get June 30, 2014. I guess it's because June doesn't have 31 days so JavaScript does it best to avoid errors.
I wrote a special function to actually do the setDate, setMonth and setYear functions on that date object based on calculations. Seems like the setMonth alone doesnt do the right thing.
Ideas,
David
Are you trying to get 1 month from now? If so, what you are getting is correct. 1 Month from May 31 is July 1, not June 30. If you want it to only move to the second month only depending on the number of days in this month:
Ex: Jan 31st 2014 -> Feb 28th 2014
or the case you mentioned, you can use a small hack to use the min of the current days and the number of days in the next month to keep you in that same month:
// Assume its yesterday
var date = new Date(2014, 4, 31);
// Get the current date
var currentDate = date.getDate();
// Set to day 1 to avoid forward
date.setDate(1);
// Increase month by 1
date.setMonth(date.getMonth() + 1);
// Get max # of days in this new month
var daysInMonth = new Date(date.getYear(), date.getMonth()+1, 0).getDate();
// Set the date to the minimum of current date of days in month
date.setDate(Math.min(currentDate, daysInMonth));
I just had this same issue, I assumed JS Date handled the number of days for me when I changed the month number. I ended up using moment instead.
Reference:
Add months/days/etc: https://momentjs.com/docs/#/manipulating/add/
Substract months/days/etc: https://momentjs.com/docs/#/manipulating/subtract/
I am trying to get how many saturdays and sundays exist between two dates.
I get the first date from a input date field
<input value="" type="date" name="exit_end_document" id="exit_end_document" class="form-control" required>
My Javascript is this:
var fromDate = $('#exit_end_document').val();
I am getting the value.. the problem is that i do not know how can i calculate between that date which i get from input date field and today.
I have seen many examples but none of them do this...
(input date field) 2019-03-01 to (This date comes directly from JS) 2019-03-05 result = 2
Thanks!
Let's analyze this mathematically.
The starting date can either be on a Saturday or not. Likewise, the ending date can be either on a Saturday or not. In the simplest case, both dates are on Saturday; then you can see clearly that the number of Saturdays is equal to 1 plus the number of weeks between the two dates.
From there, it's easy to see that if the starting date is on a Saturday, but the ending date is not, then the number of Saturdays is equal to 1 plus the number of weeks between the two dates rounded down since the ending date's week has not reached Saturday yet. Turns out, that same math works for the first example, too, since you'll have an integer number of weeks between the dates. So we can cover both examples by simply using 1 + floor(weeks_between_dates) .
What if the ending date is a Saturday, but the starting date is not? Turns out, the math still works the same! This is the same as "moving back" the starting date from its Saturday, and that will add a partial week until it reaches the previous Saturday. Those partial weeks get rounded out by the floor, and once it reaches the previous Saturday, you'll be adding 1 anyway, as it'll be a full week added to the difference! So we're still good with 1 + floor(weeks_between_dates).
So the only possible combination left are two dates which are both not Saturday. This is the most complicated possibility. Let's start simple and assume the dates are two consecutive Wednesdays. Then they are 1 week apart and have 1 Saturday between them. Simple. If they're two weeks apart, they have 2 Saturdays. But what if it's a Wednesday and the following Tuesday? There is less than a week, but still 1 Saturday between them. And if it's a Wednesday and the following Thursday? More than 1 week, but still 1 Saturday! So in this case, we'd want to round the number of weeks up and stop there, giving us ceil(weeks_between_dates). But if they're both in the same week -- for instance, a Monday and a Friday in the same week -- then the answer is just 0. So how do we know whether the days are part of the same week? Assuming they're sorted and the start date is always before the ending date, then they're in the same week if and only if there is fewer than 1 week between them AND the starting weekday is before the ending weekday.
So the straight conditional logic here is this (in pseudocode):
weeks_between = floor((days between start and end) / 7)
if start.weekday = Saturday or end.weekday = Saturday, then:
return 1 + weeks_between
else if weeks_between = 0 and start.weekday is before end.weekday, then:
return 0
else
return ceil((days between start and end) / 7)
In order to handle leap years and timezones and whatnot, i suggest testing all the between days and testing them to see if they are sat or sunday:
var date1 = new Date("2012-06-04T05:00:00.000Z");
var date2 = new Date("2012-08-17T05:00:00.000Z");
var weekendDays = 0;
for(var i = +date1, mx = +date2; i<mx; i+=(1000*60*60*24)){
if({0:1,6:1}[new Date(i).getDay()]) weekendDays++;
}
alert(weekendDays); // 20
I already found the solution and it was given from #zak:
var fromDate = $('#exit_end_document').val();
fromDate = new Date(fromDate);
toDate = new Date();
var weekendDays = 0;
dayMilliseconds = 1000 * 60 * 60 * 24;
date1 = fromDate;
date2 = toDate;
while (date1 <= date2) {
var day = date1.getDay();
if (day == 0 || day == 6) {
weekendDays++;
}
date1 = new Date(+date1 + dayMilliseconds);
}
alert(weekendDays);
I need to get the weeks starting and ending date with Javascript/ moment.js
As input i have two values: year and week, which is the isoweek of moment.js
year = '2016'
week = '1'
should give me the 04.01.2016 and 10.01.2016
where the date has the german format moment().format('DD.MM.YYYY');
The solution from your comment will produce an incorrect result on 01.01.2017:
moment([2017,0,1]).year(2017).isoWeek(1).startOf('isoweek').format('DD.MM.YYYY');
// = '04.01.2016'
This one is more stable:
//var year = 2016;
//var week = 1;
var startDate = moment([year, 5, 30]).isoWeek(week).startOf('isoweek');
var endDate = moment(startDate).endOf('isoweek');
startDate.format('DD.MM.YYYY'); // = '04.01.2016'
endDate.format('DD.MM.YYYY'); // = '10.01.2016'
Explanation: if you initialize the moment instance with a date from week 53 of the previous year in conjunction with isoWeek or week, the year component of that moment instance is set to the previous year. All additional moment methods then operate on the "wrong" year.
Therefore use moment([year, 5, 30]) to initialize the moment instance. Any other day after the Jan 3rd works for 2016 too of course, only the few days that belong to week 53 of the previous year cause that problem.
moment([2016]).isoWeek(1).startOf('isoWeek').format('DD.MM.YYYY') // "02.01.2015"
am a new for moment.js
i want 3 type of outputs
Get all months from a year
get all weeks from a month in Moment js
get all days from a week
How can i do this using moment.js?
I have tried for get all month
moment().months(2011);// it's working for my year is 2011
but i have only last 2 digits of year.
moment().months(11);// It's give wrong values or my year is 11
I also read the document, they said
moment().months() Accepts numbers from 0 to 11. If the range is exceeded, it will bubble up to the year.
This problem also accrued when i use get days and weeks
How can i solve this problem in moment.js?
Use a date as parameter (12-12-2011) find year month, month week, and week day numerical values, if you need words (Monday, December) values just use format of moment.js and translations.
A bit incorrect what you do with moment().months(2011) - moment() return date time now, months(value) add value months to your moment check and see:
moment().months(2011).format("LLLL"); //result Tuesday, August 27, 2182 ...
Now read a bit about year last week here variations between (52/53).
Now the solution for your problem,
get all months of the year, dude seriously (12 months) anyway:
moment("12-26-2011", "MM-DD-YYYY").month() + 1;
get weeks of the year not of the month (you will be confuzed using week of month)
moment("12-26-2011", "MM-DD-YYYY").week();
or try this (month week):
var curr_month = moment("12-26-2011", "MM-DD-YYYY").month();
var prev_month_last_week = moment("01-01-2011", "MM-DD-YYYY").add(curr_month -1, "month").week();
var your_week_per_month = moment("12-26-2011", "MM-DD-YYYY").week() - prev_month_last_week; //from 1 to 4:
Day of the week:
moment("12-26-2011", "MM-DD-YYYY").day();
Hope it's helpful.
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.