How to alert the starting and ending dates of previous week - javascript

How to Alert all the starting and ending dates of previous weeks.
var weekCount = 0;
$(".week-prev").live('click', function() {
var weekdate = new Date();
var fromweek = weekdate.setTime(weekdate.getTime() - 7 * 24 * 60 * 60 * 1000);
var toweek = weekdate.setTime(weekdate.getTime() - (weekdate.getDay() ? weekdate.getDay() : 7) + weekCount * 24 * 60 * 60 * 1000);
var prevweekstart = new Date(fromweek);
var prevweekends = new Date(toweek);
prevweekstart = prevweekstart.toLocaleString(),
prevweekends = prevweekends.toLocaleString(),
between = [];
alert(prevweekstart);
alert(prevweekends);
});

I would suggest to use moment.js for all date manipulations in Javascript
moment().startOf('week'); // set to the first day of this week, 12:00 am
moment().startOf('isoWeek'); // set to the first day of this week according to ISO 8601, 12:00 am
moment().endOf('week'); // set to the last day of this week, 12:00 am
moment().endOf('isoWeek'); // set to the last day of this week according to ISO 8601, 12:00 am
As of version 2.1.0, moment#startOf('week') uses the locale aware week start day.
For your example with the previous week you would use:
moment().subtract('weeks', 1).startOf('week');

Related

How can I get the first and last day of the week crossing months in javascript [duplicate]

This question already has answers here:
How to get first and last day of the current week in JavaScript
(32 answers)
Closed 2 years ago.
So for example, monday is sep 28, a week from monday, sunday is oct 4. How Can I get the first and last day of the week? So far the solutions cover only days belonging in the same month. Please help. Thanks
You can use date-fns library for that:
const start = startOfWeek(date);
const end = endOfWeek(date);
Check out these threads for more solutions:
How to get first and last day of current week when days are in different months?
How to get first and last day of the week in JavaScript
You want to look into the Date.getDay() method. This returns a number from 0-6 for the day of the week (Sunday is 0).
As a function, it could look like this:
function getMonday(date){
const originalDay = date.getDay();
const monday = 1;
const newDate = new Date(date);
const delta = originalDay === 0 ? 1 : originalDay - monday;
newDate.setDate(newDate.getDate() - delta);
return newDate;
}
You can add a week to the starting date's time and construct a new date:
const DAY = 1000 * 60 * 60 * 24; // ms * seconds * minutes * hours
const WEEK = DAY * 7;
const today = new Date('2020-09-29');
const nextWeek = new Date(today.getTime() + WEEK);
console.log(nextWeek.toUTCString());
Then add or subtract from that date to get the first/last day of the week if necessary.
const DAY = 1000 * 60 * 60 * 24;
const WEEK = DAY * 7;
const today = new Date('2020-09-29');
const nextWeek = new Date(today.getTime() + WEEK);
const day = nextWeek.getDay(); // 0 sunday, 6 saturday
const firstDay = new Date(nextWeek.getTime() - (day * DAY));
const lastDay = new Date(nextWeek.getTime() + ((6 - day) * DAY));
console.log(firstDay.toUTCString()); // monday
console.log(lastDay.toUTCString()); // sunday

Javascript: Calculate time difference between 2 days with conversion to UTC

I have a start and end dates, I need to convert them to UTC and calculate how many days are in between (including).
So for example:
(01/08/15 10:00 GMT+3) - (04/08/15 10:00 GMT+3) will return 4
(01/08/15 00:00 GMT+3) - (04/08/15 10:00 GMT+3) will return 5
The following code works for those dates like the first case, but not for the second (where after the conversion there is an additional day):
var startDateInUTC = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
var endDateInUTC = new Date(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate(), end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds());
var totalDays = Math.floor((endDateInUTC - startDateInUTC) / (1000 * 60 * 60 * 24)) + 1;
I tried changing the Math.floor to Math.round but that just adds me a day in some scenarios.
What am I doing wrong?
function calculate(start, end)
{
var startDateInUTC = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
var endDateInUTC = new Date(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate(), end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds());
return Math.floor(millisecondsToDays = (Date.parse(endDateInUTC) - Date.parse(startDateInUTC)) / 1000 / 3600 / 24);
}
console.log(calculate(new Date("2015/08/01 10:00:00"), new Date("2015/08/04 10:00:00")));
console.log(calculate(new Date("2015/08/01 00:00:00"), new Date("2015/08/04 10:00:00")));
//the answer in both cases will be 3
Use Date.parse here. It will convert the dates into timeStamps. you can subtract these and then calculate the amount back to days. Use Math.floor to round down, since 6.25 is 6 days and 6 hours.
timeStamps are the amount of milliseconds that have passed since 1970/01/01 00:00:00. That date is always UTC. When you have two timestamps you can calculate the difference between them. Date.parse() returns the timestamp on a valid date. new Date(timestamp) will return the date based upon the timestamp.
To get date barriers you can do an extra calculation:
(start time + 24 * days + end time) / 24
Round this figure down and you get the day barriers.
Example:
21 + 24 * 3 + 7 = 100
103 / 24 = 4.1666666.....
Math.floor(4.166666) = 4;
I ended up gathering a pretty simple solution combining some bits of Mouser's answer (Thanks!)
function calcStreamDaysInUTC(start, end) {
try {
// Translate to UTC
var startDateInUTC = new Date(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds());
var endDateInUTC = new Date(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate(), end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds());
// Reset everything but the date
startDateInUTC.setHours(0);
startDateInUTC.setMinutes(0);
startDateInUTC.setSeconds(0);
endDateInUTC.setHours(0);
endDateInUTC.setMinutes(0);
endDateInUTC.setSeconds(0);
var totalDays = (endDateInUTC - startDateInUTC) / (1000 * 60 * 60 * 24) + 1;
return totalDays;
} catch (e) {
return -1;
}
}

MooTools: Get the first and last days of a given week

I'm relatively inexperienced in JavaScript (we're using MooTools, here) and I'm stuck with a problem:
Is there a quick way to get the first and last dates of a given week?
e.g. week 17 / 2015 starts on Monday, April 20th and ends on Sunday, April 26th.
My goal is to find out if a given week starts and ends in the same month (week 18 wont, since it starts on April 27th and ends on May 3rd).
Many thanks on any help with examples or pointing me to the right documentation.
I've been looking for a while and haven't found anything like this, and I find MooTools documentation very poor...
Boa noite Filipe,
to do this you do not need MooTools. You can do with Vanilla JS.
Here is an idea:
function dayAnalizer(str) {
var date = new Date(str).getTime();
var weekAfter = date + 7 * 24 * 60 * 60 * 1000;
return new Date(date).getMonth() == new Date(weekAfter).getMonth();
}
console.log(dayAnalizer('10-05-2015')); // true
console.log(dayAnalizer('13-05-2015')); // false
console.log(dayAnalizer('16-05-2015')); // false
jsFiddle: http://jsfiddle.net/1g4bvgjg/
basically it gets a date in string format and converts it to timestamp (miliseconds), then create another date 1 week forward. In the end compare if both have same month.
If you need to know if a certain week in a year starts and ends in the same month you could use something like this:
function weekAnalyser(week, year) {
var days = (1 + (week - 1) * 7); // 1st of January + 7 days for each week
var date = new Date(year, 0, days);
var dayOfWeek = date.getDay(); // get week day
var firstDayOfWeek = date.getTime() - (dayOfWeek) * 60 * 60 * 24 * 1000); // rewind to 1st day of week
var endOfWeek = firstDayOfWeek + 6 * 24 * 60 * 60 * 1000;
return new Date(firstDayOfWeek).getMonth() == new Date(endOfWeek).getMonth();
}
jsFiddle: http://jsfiddle.net/zfassz29/
Ps. Welcome to Portuguese Stackoverflow: https://pt.stackoverflow.com/

Increment JavasScript date object for next month when days are increased?

Is there a simple solution to auto increment the month of the date object when days are added via getDate?
I need to add 2 days to a user supplied date, for example if the user's entered value is 2014-11-16 it returns 2014-11-18.
I have this working in the below example, but the problem is if a user supplies a date at the end of the month, for example 2014-11-30 it will return 2014-11-32 (November only has 30 days) instead of rolling into the next month, it should be 2014-12-02.
It also does not increment to a new year as well.
var actualDate = new Date(arrive);
var year = actualDate.getFullYear();
var monthy = actualDate.getMonth()+1;
var days = actualDate.getDate()+2;
var out = year + '-' + (monthy < 10 ? '0' : '') + monthy + '-' + days;
http://jsfiddle.net/bubykx1t/
Just use the setDate() method.
var actualDate = new Date(arrive);
actualDate.setDate(actualDate.getDate() + 2);
Check out this link
You can create new Date objects based on the number of milliseconds since January 1, 1970, 00:00:00 UTC. Since the number of milliseconds in a minute, hour, day, week are set we can add a fixed amount to the current time in order to get a time in the future. We can forget about what day of the month, or year it is as it's inherent in the number of milliseconds that have passed since 1970.
This will keep adjust to days months and years correctly.
var numberOfDaysToIncrement = 7;
var offset = numberOfDaysToIncrement * 24 * 60 * 60 * 1000;
var date = new Date();
var dateIncremented = new Date(date.getTime() + offset);

Add future time to date and compare

I apologize if this question has been asked already but I couldn't find it for my problem.
I have seen this but am not sure what the number it returns represents: Date() * 1 * 10 * 1000
I'd like to set a future moment in time, and then compare it to the current instance of Date() to see which is greater. It could be a few seconds, a few minutes, a few hours or a few days in the future.
Here is the code that I have:
var futureMoment = new Date() * 1 *10 * 1000;
console.log('futureMoment = ' + futureMoment);
var currentMoment = new Date();
console.log('currentMoment = ' + currentMoment);
if ( currentMoment < futureMoment) {
console.log('currentMoment is less than futureMoment. item IS NOT expired yet');
}
else {
console.log('currentMoment is MORE than futureMoment. item IS expired');
}
Javascript date is based on the number of milliseconds since the Epoch (1 Jan 1970 00:00:00 UTC).
Therefore, to calculate a future date you add milliseconds.
var d = new Date();
var msecSinceEpoch = d.getTime(); // date now
var day = 24 * 60 * 60 * 1000; // 24hr * 60min * 60sec * 1000msec
var futureDate = new Date(msecSinceEpoc + day);
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var futureMoment = new Date() * 1 *10 * 1000;
becomes
var now = new Date();
var futureMoment = new Date(now.getTime() + 1 *10 * 1000);
I think you mean to add time. Not multiply it.
If you deal with time, there is a lot of tools to choose.
Try moment library.
Used following code to compare selected date time with current date time
var dt = "Thu Feb 04 2016 13:20:02 GMT+0530 (India Standard Time)"; //this date format will receive from input type "date"..
function compareIsPastDate(dt) {
var currDtObj = new Date();
var currentTime = currDtObj.getTime();
var enterDtObj = new Date(dt);
var enteredTime = enterDtObj.getTime();
return (currentTime > enteredTime);
}

Categories

Resources