Momentjs - Get most recent Friday - javascript

I'm trying to get the start of (12:00am, or, 00:00am) of the most recent Friday. This has been working:
moment().isoWeekday(5).startOf('day').toDate()
But it only works Friday->Sunday, on Monday morning it will then refer to the upcoming Friday, in which case this would work:
moment().add('-1', 'week').day(5).startOf('day').toDate()
but I need it be dynamic and done in one line if possible, to where I don't to perform any checks on the current day.
Is there a way to always get the most recent Friday? Regardless of what the current day is.
Edit I'm also trying to get this to return the current day (friday) if executed on a Friday.

If you don't want to use a library, it's pretty straight forward
var date = new Date();
while ( date.getDay() !== 5 ) date.setDate(date.getDate() -1);
console.log(date)
With moment
var date = moment();
var friday = date.day(date.day() >= 5 ? 5 :-2);
and if millisecond accuracy doesn't matter, you could call moment() twice to make it one line (but I would much raher use a variable)
var friday = moment().day(moment().day() >= 5 ? 5 :-2);

Check this:
var date = moment().utc().isoWeekday(5);
if(moment().day() < 5) {
date = date.add(-1, 'week');
}
console.log('Recent friday starts:', date.startOf('day').toDate());
console.log('Recent friday ends:', date.endOf('day').toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.js"></script>

Related

Moment check next month

I'd like to check the date if it's next month from the current.
Some test cases here
2020.1.1 2019.12.30 // true
2019.11.30 2019.10.10 // true
2019.12.11 2019.12.1 // false
So as you can see, I'd like to check if the date is next month from now.
Hope to get the brilliant idea!
Best
Kinji
You could try this approach, we have to handle the case when the dates are in the same year and also for December and January of the next year.
A simple algorithm can be created, whereby we multiply the year by 12, add the month and get the difference of this score between the two dates. As long as the value of this is 1 or -1 we have months that are adjacent. I'm presuming you only need to check if the first parameter is the next month to the second parameter, so we check for a difference of 1.
function isNextMonth(timeStamp1, timeStamp2, format = "YYYY.MM.DD") {
let dt1 = moment(timeStamp1, format);
let dt2 = moment(timeStamp2, format);
return ((dt1.year()*12 + dt1.month() - dt2.year()*12 - dt2.month()) === 1);
}
let inputs = [['2020.1.1','2019.12.30'],['2019.11.30', '2019.10.10'], ['2019.12.11','2019.12.1'], ['2020.12.1','2021.1.1'], ['2020.6.1','2020.5.1'], ['2021.1.1','2019.12.1'], ['2019.3.1', '2019.4.1']];
for(let [inputa, inputb] of inputs) {
console.log(`isNextMonth(${inputa}, ${inputb}): ${isNextMonth(inputa, inputb)}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
A very simple solution would be to use Moment’s isSame. This only checks the month. If you also want to make sure that the year matches you would have to make sure that nextMonth.getYear() matches dateToCheck.getYear()
var dateToCheck = new Date(2019, 11, 30)
var nextMonth = new Date()
nextMonth.setMonth(dateToCheck.getMonth() + 1)
moment(dateToCheck).isSame(nextMonth, 'month');

How do I change something depending on date?

So what I need to try an accomplish is to output a specific message depending on how close a date is. The task is to change an element of a webpage from a message saying "Renewal Unnecessary" when the date is more than 3 months away, "Renewal upcoming" when the date is less than 3 months away, and finally "Renewal Required!" when the date is 1 month away.
So far I have:
if()
{<hre>Renewal Required!</hre>}
else if()
{<ha>Renewal upcoming</ha>}
else
{<hg>Renewal Unnecessary</hg>}
I am uncertain of how to write the condition for what i need the script to do, for example the renewal month or date might be the 26th February, and is there some way of making it work off the computers date.
Date.now returns currrent date in miliseconds. Just check for
renewal_date - Date.now()
And compare it with the corrent number of miliseconds.
Here's one way you could do it. You could expand this to be considerate of what day of the month it is, also. Live demo (click).
var deadline = new Date(2014, 1, 2); //2014, February 2nd (January is Month 0)
var today = new Date();
var monthDiff = deadline.getMonth() - today.getMonth();
if (monthDiff < 3) {
console.log('Deadline is in 3 months or less!');
}
if (monthDiff <= 1) {
console.log('Deadline is in 1 month or less!');
}
Answering your comment: There a are lots of ways this can be done - learn the basics. Here are two examples that might help.
var p = document.createElement('p);
p.textContent = 'My message here';
document.body.appendChild(p);
Or if the element already exists on the page:
var elem = document.getElementById('myElem');
elem.textContent = 'My message here';

How does weekly reminders work?

Is there an algorithm for weekly reminders ?
For example, I set a reminder for Thursday & I check the "weekly" option.
The Reminder is supposed to alert every Thursday then,but how is this done?
I thought about an idea, but I guess it's very stupid:
Get today's "day".
Get today's "date".
Get the wanted day number.
Subtract both days from each other.
using [4] get that day's date.
Increment the counter after every alert with 7.
I don't even know whether this will work or not, I'm sure there is a better way to do it, so I need your opinions before starting implementation.
PS: I use JavaScript so the functions are very limited.
It's not entirely clear what you're trying to do.
If your code needs to know whether it's Thursday, that's really easy using getDay, which gives you the day of the week:
if (new Date().getDay() === 4) {
// It's Thursday
}
The day numbers start with 0 = Sunday.
If your code needs to find the next Thursday starting on a given date:
var dt = /* ...the start date... */;
while (dt.getDay() !== 4) {
dt.setTime(dt.getTime() + 86400000)) // 86400000 = 1 day in milliseconds
}
or of course without the loop:
var dt = /* ...the start date... */;
var days = 4 - dt.getDay();
if (days < 0) {
days += 7;
}
dt.setTime(dt.getTime() + (days * 86400000));
If you have a Thursday already and you need to know the date for the next Thursday:
var nextThursday = new Date(thisThursday.getTime() + (86400000 * 7));

JavaScript time question

I am new to JavaScript but need to run a check to make sure it is daylight. I am using yahoo's weather API to pull sunrise and sunset. I'm just a little confused as to the best approach for comparing its results to the current time.
I am confused because it returns a time like sunset: '9:01 pm'. bsince there is a PM it is text. I can't think of a good way to compare it to the current time... RegExp, then convert to an integer maybe?
What would be the best approach to this, and why (sorry I'm trying to learn)?
Thanks in advance for any help.
Create a new Date() with the info from yahoo's api, then compare Date.now() with sunsetDate.getTime() and sunriseDate.getTime().
Passing today's date in mm/dd/yyyy format with the time as '9:01 pm' to the Date constructor will give you a valid date.
var today = new Date();
today = [today.getMonth()+1, today.getDate(), today.getFullYear()].join('/');
var yahooSunrise = '5:45 am';
var yahooSunset = '9:01 pm';
var sunrise = new Date(today + ' ' + yahooSunrise).getTime();
var sunset = new Date(today + ' ' + yahooSunset).getTime();
var now = Date.now();
var isDaylight = (now > sunrise && now < sunset);
This would work with something like this, but maybe you might need to change the timings to suite a particular climate:
function getNow() {
var now = new Date
if (now.getHours() < 5) { return "Could be still dark";}
else if (now.getHours() < 9) {return "Definitely day time";}
else if (now.getHours() < 17) { return "Definitely day time"; }
else {return "It gets dark now";}
}
alert(getNow());
One quick approach is to turn both the current time of day and the time you get back from yahoo into the value "minutes since the beginning of the day."
For example, if Yahoo gives you 9:01pm, use the pm to turn the time into 21:01. That is
21*60 + 1 = 1260 + 1 = 1261 minutes since the beginning of the day
Do this for both sunrise and suset. Then get the current time with
new Date()
and do the same kind of thing.
Then just do integer comparisons!
Hope that helps.
This sounds like a good candiidate for a regular expression on the data you get back from the service.
Something like (\d{1,2}):(\d{2})\s(AM|PM) will give you 3 capture groups.
1: The hour (1 or 2 digits)
2: The Minute (2 digits)
3: Either string "AM" or "PM"
You can then use these to parse out the actual time as integer hour and minute to compare to the current time.

the closest Sunday before given date with JavaScript

I need to know the date for last Sunday for given date in php & javascript
Let's have a function give_me_last_Sunday
give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529
The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.
My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.
Based on Thomas' effort, and provided the input string is exactly the format you specified, then:
function lastSunday(d) {
var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
d = new Date(d);
d.setDate(d.getDate() - d.getDay());
return d;
}
Edit
If I were to write that now, I'd not depend on the Date object parsing the string but do it myself:
function lastSunday(s) {
var d = new Date(s.substring(0,4), s.substring(4,6) - 1, s.substring(6));
d.setDate(d.getDate() - d.getDay());
return d;
}
While the format yyyy/mm/dd is parsed correctly by all browsers I've tested, I think it's more robust to stick to basic methods. Particularly when they are likely more efficient.
Ok so this is for JavaScript only. You have an input that you need to extract the month, date, and year from. The following is just partly an answer then on how to get the date:
<script type="text/javascript">
var myDate=new Date();
myDate.setFullYear(2011,4,16)
var a = myDate.getDate();
var t = myDate.getDay();
var r = a - t;
document.write("The date last Sunday was " + r);
</script>
So the setFullYear function sets the myDate to the date specified where the first four digits is the year, the next are is the month (0= Jan, 1= Feb.,...). The last one is the actually date. Then the above code gives you the date of the Sunday before that. I am guessing that you can add more code to get the month (use getMonth() method). Here are a few links that might be helpful
http://www.w3schools.com/js/js_obj_date.asp
http://www.w3schools.com/jsref/jsref_setFullYear.asp
http://www.w3schools.com/jsref/jsref_getMonth.asp
(You can probably find the other functions that you need)
I hope this helps a bit even though it is not a complete answer.
Yup and strtotime has been ported to JS for eg http://phpjs.org/functions/strtotime:554 here.
final code (big thanks to #Thomas & #Rob)
function lastSunday(d) {
var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
d = new Date(d);
d.setDate(d.getDate() - d.getDay());
year = d.getFullYear()+'';
month = d.getMonth()+1+'';
day = d.getDate()+'';
if ( month.length == 1 ) month = "0" + month; // Add leading zeros to month and date if required
if ( day.length == 1 ) day = "0" + day;
return year+month+day;
}

Categories

Resources