Javascript: Calculate time between today and a specific following weekday time - javascript

I'm looking for a method to calculate the time in seconds between now UTC-7 and the following Saturday (independent of the date the calculation is being done) at a specific UTC-7 time (08:00) in Javascript.
Currently I am using this code but i want to replace giving specific dates with the abovementioned calculation:
// Grab the current date
var now = new Date();
var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()); currentDate.setHours(currentDate.getHours() - 7);
// Set some date in the future.
var ClashDate = new Date("August 6, 2017 16:40:00");
var BashDate = new Date("August 12, 2017 08:00:00");
// Calculate the difference in seconds between the future and current date
var diffclash = ClashDate.getTime() / 1000 - currentDate.getTime() / 1000;
var diffbash = BashDate.getTime() / 1000 - currentDate.getTime() / 1000;
Could anyone help me out?
Yours sincerely
Yamper

In POJS, (one way) you can get the next Saturday at a particular time as follows.
function nextSaturday(date) {
const d = date ? new Date(date) : new Date();
d.setDate(d.getDate() + (6 - d.getDay()) % 7);
return new Date(`${d.toISOString().split('T').shift()}T14:00:00.000Z`);
}
console.log(nextSaturday('2017-08-13'));
console.log(nextSaturday('2017-08-31'));
console.log(nextSaturday());

For simplicity you can use MomentJS to dynamically figure out the dates for the following Saturday and the next Saturday after it.
To instance a Moment date for this coming Saturday you can do it through the .day(int) API. E.g. .day(6).
To get the epoch time you can do .unix() but there is a catch here. By default it returns you seconds since epoch not the standard milliseconds.
Example:
var now = new Date();
var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()); currentDate.setHours(currentDate.getHours() - 7);
moment().tz("America/New_York").format();
// Set some date in the future.
var ClashDate = moment().day("Saturday").hour(16).minutes(40).seconds(0);
var BashDate = moment().day(13).hour(8).minutes(0).seconds(0);
console.log("Next Saturday date is => " + ClashDate.toString());
console.log("Next Next Saturday date is => " + BashDate.toString());
// Calculate the difference in seconds between the future and current date
var diffclash = ClashDate.unix() - currentDate.getTime() / 1000;
var diffbash = BashDate.unix() - currentDate.getTime() / 1000;
console.log("diffClash => " + diffclash);
console.log("diffBash => " + diffbash);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data.min.js"></script>
Reference:
MomentJS - https://momentjs.com/docs/

Related

How do you get the Unix timestamp for the end of today in Javascript?

I want to get the end Unix timestamp of today.
Get start timestamp of today using this but I want end timestamp of today
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay / 1000;
864e5 is the number of milliseconds in a day (24 * 60 * 60 * 1000), and now % 864e5 is the time part of the date in milliseconds :
var now = new Date
var startOfDay = new Date(now - now % 864e5)
var endOfDay = new Date(now - now % 864e5 + 864e5 - 1)
console.log(now)
console.log(startOfDay)
console.log(endOfDay)
You can use .valueOf() method, to get milliseconds timestamp from date, instead of date / 1000
To get end of the day, just take next day date and reduce for 1 millisecond
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
// take next day date and reduce for one millisecond
var endOfDay = new Date(new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1) - 1);
console.log({
startOfDay,
endOfDay,
startOfDayTimestamp: startOfDay.valueOf(),
endOfDayTimestamp: endOfDay.valueOf()
})
At First, get today timestamp:
var now = new Date();
Then get the start of tomorrow:
var startOfTomorrow = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDay() + 1);
Now you have end of today:
var timestampOfEndOfDay = (startOfTomorrow - 1);
See the result:
console.log("End of the Day", new Date(timestampOfEndOfDay) );

Calculate time remaining between now and a precise hour of next day

What's the most concise, performant way to get in Javascript the minutes remaining between now, and the upcoming day at 01:00 (am)?
Then, once the current time is after 01:00, I start calculating the difference to the next.
in javascript, a specified date can be provided like this
var date1 = new Date('June 6, 2019 03:24:00');
or it can be specified like this
var date2 = new Date('2019-6-6T03:24:00');
javascript can natively subtract 2 dates
console.log(date1 - date2);
//expected 0;
using this method will output the difference in the dates in milliseconds,
to get minutes you'll want to divide the value by 60000;
so
var futureTime = new Date('2019-06-06T07:24:00');
//there must be a 0 infront of 1 digit numbers or it is an invalid date
var now = new Date();
var difference = (futureTime - now) / 60000;
//get minutes by dividing by 60000
//doing Date() with no arguments returns the current date
read about the javascript Date object here for more information
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
let now = new Date();
let next1am = new Date();
next1am.setHours(1, 0, 0, 0); // same as now, but at 01:00:00.000
if (next1am < now) next1am.setDate(next1am.getDate() + 1); // bump date if past
let millisecondDiff = next1am - now;
let minuteDiff = Math.floor(millisecondDiff / 1000 / 60);
you can you moment.js here
var current = new Date()
var end = new Date(start.getTime() + 3600*60)// end time to calculate diff
var minDiff = end - start; // in millisec
You can calculate by pure JavaScript:
let today = new Date();
let [y,M,d,h,m,s] = '2019-06-04 05:00:11'.split(/[- :]/);
let yourDate = new Date(y,parseInt(M)-1,d,h,parseInt(m)+30,s);
let diffMs = (yourDate - today);
let diffDays = Math.floor(diffMs / 86400000); // days
let diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
let diffMins = (diffDays * 24 * 60)
+ (diffHrs *60)
+ Math.round(((diffMs % 86400000) % 3600000) / 60000); // The overall result
// in minutes
In, addition avoid using the built–in parser for any non–standard format, e.g. in Safari new Date("2019-04-22 05:00:11") returns an invalid date. You really shouldn't even use if for standardized formats as you will still get unexpected results for some formats. Why does Date.parse give incorrect results?

Setting Javascript Date in future

I'm editing a countdown clock but unsure how to set the future date in javascript. The example set's it for the next New Years. I need to set it as a fixed date, 27th April 2015.
// Grab the current date
var currentDate = new Date();
// Set some date in the future. In this case, it's always Jan 1
var futureDate = new Date(currentDate.getFullYear() + 1, 0, 1);
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
I'm just unsure how to set the future date correctly to be the 27 April 2015.
Thanks!
Matt
var d = new Date();
d.setDate(27);
d.setMonth(3);
d.setYear(2015);
console.log(d);
This is how you add days to a date:
var currentDate = new Date();
futureDate.setDate(currentDate.getDate() + 10 /* 10 days */ );
Did you just want to set it to April 27th of the next year? If so this should work.
var futureDate = new Date(currentDate.getFullYear() + 1, 3, 27);
Working JS Fiddle:
http://jsfiddle.net/Kitchenfinks/xukwLbdk/

How do you get the unix timestamp for the start of today in javascript?

I realize that the current timestamp can be generated with the following...
var timestamp = Math.round((new Date()).getTime() / 1000);
What I'd like is the timestamp at the beginning of the current day. For example the current timestamp is roughly 1314297250, what I'd like to be able to generate is 1314230400 which is the beginning of today August 25th 2011.
Thanks for your help.
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay / 1000;
Well, the cleanest and fastest way to do this is with:
long timestamp = 1314297250;
long beginOfDay = timestamp - (timestamp % 86400);
where 86400 is the number of seconds in one day
var now = new Date; // now
now.setHours(0); // set hours to 0
now.setMinutes(0); // set minutes to 0
now.setSeconds(0); // set seconds to 0
var startOfDay = Math.floor(now / 1000); // divide by 1000, truncate milliseconds
var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
var t = d / 1000;
Alternatively you could subtract the modulo of a days length in miliseconds e.g.
var day = 24*60*60*1000;
var start_of_today = Date.now() - Date.now() % day;
Luis Fontes' solution returns UTC time so it can be 1 hour (daylight saving time) different from setHours solution.
var d = new Date();
var t = d - (d % 86400000);
Simplified version of examples above (local time).
var d = new Date();
d.setHours(0,0,0,0);
var t = d / 1000;
Here you can find some performance tests: http://jsperf.com/calc-start-of-day
Another alternative for getting the beginning of the day is the following:
var now = new Date();
var beginningOfDay = new Date(now.getTime() -
now.getHours() * 60 * 60 * 1000 -
now.getMinutes() * 60 * 1000 -
now.getSeconds() * 1000 -
now.getMilliseconds());
var yoursystemday = new Date(new Date().getTime()-(120000*60+new Date().getTimezoneOffset()*60000));
yoursystemday = new Date();
var current_time_stamp = Math.round(yoursystemday.getTime()/1000);
For any date it's easy to get Timestamps of start/end of the date using ISO String of the date ('yyyy-mm-dd'):
var dateString = '2017-07-13';
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
To get ISO String of today you would use (new Date()).toISOString().substring(0, 10)
So to get TS for today:
var dateString = (new Date()).toISOString().substring(0, 10);
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();
var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay.getTime() / 1000;

How to subtract days from a plain Date?

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Is there an easy way of taking a olain JavaScript Date (e.g. today) and going back X days?
So, for example, if I want to calculate the date 5 days before today.
Try something like this:
var d = new Date();
d.setDate(d.getDate()-5);
Note that this modifies the date object and returns the time value of the updated date.
var d = new Date();
document.write('Today is: ' + d.toLocaleString());
d.setDate(d.getDate() - 5);
document.write('<br>5 days ago was: ' + d.toLocaleString());
var dateOffset = (24*60*60*1000) * 5; //5 days
var myDate = new Date();
myDate.setTime(myDate.getTime() - dateOffset);
If you're performing lots of headachy date manipulation throughout your web application, DateJS will make your life much easier:
http://simonwillison.net/2007/Dec/3/datejs/
It goes something like this:
var d = new Date(); // today!
var x = 5; // go back 5 days!
d.setDate(d.getDate() - x);
I noticed that the getDays+ X doesn't work over day/month boundaries. Using getTime works as long as your date is not before 1970.
var todayDate = new Date(), weekDate = new Date();
weekDate.setTime(todayDate.getTime()-(7*24*3600000));
If you want it all on one line instead.
5 days from today
//past
var fiveDaysAgo = new Date(new Date().setDate(new Date().getDate() - 5));
//future
var fiveDaysInTheFuture = new Date(new Date().setDate(new Date().getDate() + 5));
5 days from a specific date
var pastDate = new Date('2019-12-12T00:00:00');
//past
var fiveDaysAgo = new Date(new Date().setDate(pastDate.getDate() - 5));
//future
var fiveDaysInTheFuture = new Date(new Date().setDate(pastDate.getDate() + 5));
I wrote a function you can use.
function AddOrSubractDays(startingDate, number, add) {
if (add) {
return new Date(new Date().setDate(startingDate.getDate() + number));
} else {
return new Date(new Date().setDate(startingDate.getDate() - number));
}
}
console.log('Today : ' + new Date());
console.log('Future : ' + AddOrSubractDays(new Date(), 5, true));
console.log('Past : ' + AddOrSubractDays(new Date(), 5, false));
I find a problem with the getDate()/setDate() method is that it too easily turns everything into milliseconds, and the syntax is sometimes hard for me to follow.
Instead I like to work off the fact that 1 day = 86,400,000 milliseconds.
So, for your particular question:
today = new Date()
days = 86400000 //number of milliseconds in a day
fiveDaysAgo = new Date(today - (5*days))
Works like a charm.
I use this method all the time for doing rolling 30/60/365 day calculations.
You can easily extrapolate this to create units of time for months, years, etc.
get moment.js. All the cool kids use it. It has more formatting options, etc. Where
var n = 5;
var dateMnsFive = moment(<your date>).subtract(n , 'day');
Optional! Convert to JS Date obj for Angular binding.
var date = new Date(dateMnsFive.toISOString());
Optional! Format
var date = dateMnsFive.format("YYYY-MM-DD");
A few of the existing solutions were close, but not quite exactly what I wanted. This function works with both positive or negative values and handles boundary cases.
function addDays(date, days) {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() + days,
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
Without using the second variable, you can replace 7 for with your back x days:
let d=new Date(new Date().getTime() - (7 * 24 * 60 * 60 * 1000))
I made this prototype for Date so that I could pass negative values to subtract days and positive values to add days.
if(!Date.prototype.adjustDate){
Date.prototype.adjustDate = function(days){
var date;
days = days || 0;
if(days === 0){
date = new Date( this.getTime() );
} else if(days > 0) {
date = new Date( this.getTime() );
date.setDate(date.getDate() + days);
} else {
date = new Date(
this.getFullYear(),
this.getMonth(),
this.getDate() - Math.abs(days),
this.getHours(),
this.getMinutes(),
this.getSeconds(),
this.getMilliseconds()
);
}
this.setTime(date.getTime());
return this;
};
}
So, to use it i can simply write:
var date_subtract = new Date().adjustDate(-4),
date_add = new Date().adjustDate(4);
I like doing the maths in milliseconds. So use Date.now()
var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds
and if you like it formatted
new Date(newDate).toString(); // or .toUTCString or .toISOString ...
NOTE: Date.now() doesn't work in older browsers (eg IE8 I think). Polyfill here.
UPDATE June 2015
#socketpair pointed out my sloppiness. As s/he says "Some day in year have 23 hours, and some 25 due to timezone rules".
To expand on that, the answer above will have daylightsaving inaccuracies in the case where you want to calculate the LOCAL day 5 days ago in a timezone with daylightsaving changes and you
assume (wrongly) that Date.now() gives you the current LOCAL now time, or
use .toString() which returns the local date and therefore is incompatible with the Date.now() base date in UTC.
However, it works if you're doing your math all in UTC, eg
A. You want the UTC date 5 days ago from NOW (UTC)
var newDate = Date.now() + -5*24*3600*1000; // date 5 days ago in milliseconds UTC
new Date(newDate).toUTCString(); // or .toISOString(), BUT NOT toString
B. You start with a UTC base date other than "now", using Date.UTC()
newDate = new Date(Date.UTC(2015, 3, 1)).getTime() + -5*24*3600000;
new Date(newDate).toUTCString(); // or .toISOString BUT NOT toString
split your date into parts, then return a new Date with the adjusted values
function DateAdd(date, type, amount){
var y = date.getFullYear(),
m = date.getMonth(),
d = date.getDate();
if(type === 'y'){
y += amount;
};
if(type === 'm'){
m += amount;
};
if(type === 'd'){
d += amount;
};
return new Date(y, m, d);
}
Remember that the months are zero based, but the days are not. ie new Date(2009, 1, 1) == 01 February 2009, new Date(2009, 1, 0) == 31 January 2009;
Some people suggested using moment.js to make your life easier when handling dates in js. Time has passed since those answers and it is noteworthy, that the authors of moment.js now discourage its use. Mainly due to its size and lack of tree-shaking-support.
If you want to go the library route, use an alternative like Luxon. It is significantly smaller (because of its clever use of the Intl object and support for tree-shaking) and just as versatile as moment.js.
To go back 5 days from today in Luxon, you would do:
import { DateTime } from 'luxon'
DateTime.now().minus({ days: 5 });
function addDays (date, daysToAdd) {
var _24HoursInMilliseconds = 86400000;
return new Date(date.getTime() + daysToAdd * _24HoursInMilliseconds);
};
var now = new Date();
var yesterday = addDays(now, - 1);
var tomorrow = addDays(now, 1);
See the following code, subtract the days from the current date. Also, set the month according to substracted date.
var today = new Date();
var substract_no_of_days = 25;
today.setTime(today.getTime() - substract_no_of_days* 24 * 60 * 60 * 1000);
var substracted_date = (today.getMonth()+1) + "/" +today.getDate() + "/" + today.getFullYear();
alert(substracted_date);
I have created a function for date manipulation. you can add or subtract any number of days, hours, minutes.
function dateManipulation(date, days, hrs, mins, operator) {
date = new Date(date);
if (operator == "-") {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() - durationInMs);
} else {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() + durationInMs);
}
return newDate;
}
Now, call this function by passing parameters. For example, here is a function call for getting date before 3 days from today.
var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");
Use MomentJS.
function getXDaysBeforeDate(referenceDate, x) {
return moment(referenceDate).subtract(x , 'day').format('MMMM Do YYYY, h:mm:ss a');
}
var yourDate = new Date(); // let's say today
var valueOfX = 7; // let's say 7 days before
console.log(getXDaysBeforeDate(yourDate, valueOfX));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
The top answers led to a bug in my code where on the first of the month it would set a future date in the current month. Here is what I did,
curDate = new Date(); // Took current date as an example
prvDate = new Date(0); // Date set to epoch 0
prvDate.setUTCMilliseconds((curDate - (5 * 24 * 60 * 60 * 1000))); //Set epoch time
I like the following because it is one line. Not perfect with DST changes but usually good enough for my needs.
var fiveDaysAgo = new Date(new Date() - (1000*60*60*24*5));
Using Modern JavaScript function syntax
const getDaysPastDate = (daysBefore, date = new Date) => new Date(date - (1000 * 60 * 60 * 24 * daysBefore));
console.log(getDaysPastDate(1)); // yesterday
A easy way to manage dates is use Moment.js
You can use add. Example
var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
new_date.add(5, 'days'); //Add 5 days to start date
alert(new_date);
Docs http://momentjs.com/docs/#/manipulating/add/
for me all the combinations worked fine with below code snipplet ,
the snippet is for Angular-2 implementation ,
if you need to add days , pass positive numberofDays , if you need to substract pass negative numberofDays
function addSubstractDays(date: Date, numberofDays: number): Date {
let d = new Date(date);
return new Date(
d.getFullYear(),
d.getMonth(),
(d.getDate() + numberofDays)
);
}
I get good mileage out of date.js:
http://www.datejs.com/
d = new Date();
d.add(-10).days(); // subtract 10 days
Nice!
Website includes this beauty:
Datejs doesn’t just parse strings, it slices them cleanly in two
If you want to both subtract a number of days and format your date in a human readable format, you should consider creating a custom DateHelper object that looks something like this :
var DateHelper = {
addDays : function(aDate, numberOfDays) {
aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
return aDate; // Return the date
},
format : function format(date) {
return [
("0" + date.getDate()).slice(-2), // Get day and pad it with zeroes
("0" + (date.getMonth()+1)).slice(-2), // Get month and pad it with zeroes
date.getFullYear() // Get full year
].join('/'); // Glue the pieces together
}
}
// With this helper, you can now just use one line of readable code to :
// ---------------------------------------------------------------------
// 1. Get the current date
// 2. Subtract 5 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), -5));
(see also this Fiddle)
To calculate relative time stamps with a more precise difference than whole days, you can use Date.getTime() and Date.setTime() to work with integers representing the number of milliseconds since a certain epoch—namely, January 1, 1970. For example, if you want to know when it’s 17 hours after right now:
const msSinceEpoch = (new Date()).getTime();
const fortyEightHoursLater = new Date(msSinceEpoch + 48 * 60 * 60 * 1000).toLocaleString();
const fortyEightHoursEarlier = new Date(msSinceEpoch - 48 * 60 * 60 * 1000).toLocaleString();
const fiveDaysAgo = new Date(msSinceEpoch - 120 * 60 * 60 * 1000).toLocaleString();
console.log({msSinceEpoch, fortyEightHoursLater, fortyEightHoursEarlier, fiveDaysAgo})
reference
function daysSinceGivenDate (date) {
const dateInSeconds = Math.floor((new Date().valueOf() - date.valueOf()) / 1000);
const oneDayInSeconds = 86400;
return Math.floor(dateInSeconds / oneDayInSeconds); // casted to int
};
console.log(daysSinceGivenDate(new Date())); // 0
console.log(daysSinceGivenDate(new Date("January 1, 2022 03:24:00"))); // relative...
First arg is the date to start with and second is how mush day you want to increase or reduce to the date
example (1)- pass -1 to reduce date by one day
example (2)- pass 1 to increase date by one day
const EditDay = (date: Date, num: number): Date => {
return new Date(date.getTime() + num * 24 * 60 * 60 * 1000)
}
When setting the date, the date converts to milliseconds, so you need to convert it back to a date:
This method also take into consideration, new year change etc.
function addDays( date, days ) {
var dateInMs = date.setDate(date.getDate() - days);
return new Date(dateInMs);
}
var date_from = new Date();
var date_to = addDays( new Date(), parseInt(days) );
You can using Javascript.
var CurrDate = new Date(); // Current Date
var numberOfDays = 5;
var days = CurrDate.setDate(CurrDate.getDate() + numberOfDays);
alert(days); // It will print 5 days before today
For PHP,
$date = date('Y-m-d', strtotime("-5 days")); // it shows 5 days before today.
echo $date;
Hope it will help you.
I converted into millisecond and deducted days else month and year won't change and logical
var numberOfDays = 10;//number of days need to deducted or added
var date = "01-01-2018"// date need to change
var dt = new Date(parseInt(date.substring(6), 10), // Year
parseInt(date.substring(3,5), 10) - 1, // Month (0-11)
parseInt(date.substring(0,2), 10));
var new_dt = dt.setMilliseconds(dt.getMilliseconds() - numberOfDays*24*60*60*1000);
new_dt = new Date(new_dt);
var changed_date = new_dt.getDate()+"-"+(new_dt.getMonth()+1)+"-"+new_dt.getFullYear();
Hope helps

Categories