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).
Related
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/
I need to create few records on Mondays using an api.
And the rule to get the Monday is that it should be either first Monday of a given month or last Monday of the given month.
For example:
If the input date range is 1 Sep 2020 - 30 Sep 2020, I need to pull 28 Sep 2020.
If the input date range is 1 Oct 2020 - 31 Oct 2020, I need to pull 26 Oct 2020.
If the input date range is 1 Nov 2020 - 30 Nov 2020, I need to pull 30 Nov 2020.
If the input date range is 1 Nov 2020 - 31 Dec 2020, I need to pull 28 Dec 2020.
What I did so far is I pulled all the Mondays of given month and stored them in an array. I tried pulling 1st or last Monday of the month, but this works for few months and not for few others.
Hence, I was thinking if I get to know the week of a given day(Monday), which overlaps 2 months, then I can pull that Monday.
So my question is how to get Monday of the week which overlaps 2 months? I am using moment js.
Maybe too late, but it could be helpful for future viewers.
The function takes start and end, but we only use end, so you can get rid of start as all the operations will be on end date in order to get the last monday. To achieve our goal we need to do two simple steps:
Get the end of the month with the end date.
Get the monday of the previous "calculated" date.
For the first step, we use End of Time in order to get the end of the month (the last day).
Mutates the original moment by setting it to the end of a unit of time.
Then we can get the Monday of the week the date is, and we can use Date of Week with the date of previous step.
Gets or sets the day of the week. [...] As of 2.1.0, a day name is also supported. This is parsed in the moment's current locale.
And taking your examples, we can test our function:
function lastMonday(start, end) {
console.log('Start is ', moment(start).format('LL'));
console.log('End is ', moment(end).format('LL'));
return moment(end).endOf('month').day('Monday');
}
console.log('Last monday is', lastMonday('2020-09-01', '2020-09-30').format('LL'));
console.log('Last monday is', lastMonday('2020-10-01', '2020-10-31').format('LL'));
console.log('Last monday is', lastMonday('2020-11-01', '2020-11-30').format('LL'));
console.log('Last monday is', lastMonday('2020-11-01', '2020-12-31').format('LL'));
<script src="https://momentjs.com/downloads/moment.js"></script>
I have a problem with the date recognition of Google Apps Script. I have a code where I need to add days to a given date. However, the code returns the wrong month (higher not lower what would be a typical GAS problem). I wrote the following code to test the behaviour:
var datumStart = new Date();
datumStart = arrayTimesheet[5][7];
var datum2 = new Date();
datum2.setDate(datumStart.getDate());
and I receive the following results for the two variables:
datumStart Date Mon Feb 17 2020 09:00:00 GMT+0100 (Central European Standard Time)
datum2 Date Tue Mar 17 2020 22:50:39 GMT+0100 (Central European Standard Time)
the Array[5][7] is the value of a Google Sheets cell with the value 2020-17-02.
This datum2 variable is just a test variable to understand the error.
Has anybody an idea what is going wrong?
Javascripts getDate() and setDate() functions get and set the Day of the month.
So, your code is behaving as expected, you are instantiating the date datum2 in March, so it is a date in March (current date/time), later, you use setDate() to set it to the 17th of March.
To add days to a date, you can instantiate a new date using values from your existing date, plus the additional days, eg here we are getting a date 5 days in the future:
var future_day = new Date(datumStart.getFullYear(),datumStart.getMonth(),datum.getDate()+5);
Note that Javascript's underlying Date logic is solid, if your number of days crosses a month or year boundary, the results will be correct. (for example, if you add 31 days, you'll get the correct date in the following month)
Is there a way to get the Sunday thru Saturday dates of the week based on week number?
For example the current week number is 32, so I would want an array (or some return type) as such:
["Sunday, July 3rd, 2016", "Monday, July 4th, 2016".... etc ]
The documentation here states that use can use the syntax below, however this seems to simply gives me the current day (unless I'm reading the output wrong).
moment().weeks(32)
Output: Fri Aug 05 2016 11:19:39 GMT-0400
Would suggest to not go for additional libraries. Once you get first day for given week number using moment().weeks(32), write a simple method to return next seven days using moment().add() method.
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());