Setting Javascript Date in future - javascript

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/

Related

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

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/

JS/PHP, time of date

i would like to ask, if someone know to to make in JS or PHP time of date.
Or how long we're together, like 70 days or 2 month and some days, and all day add 1 more day. I have something whats work, but on begging of that time is - .
I spent a lot time with making something what should work. But nothing.
There is that code with that -
<script charset="UTF-8">
function daysTill() {
var day= 8
var month= 12
var year= 2016
var event= "relationship with my ♥"
var end = "days of"
var daystocount=new Date(year, month -1, day)
today=new Date()
if (today.getMonth()==month && today.getDate()>day)
daystocount.setFullYear(daystocount.getFullYear())
var oneday=1000*60*60*24
var write = (Math.ceil((daystocount.getTime()-today.getTime())/(oneday)))
document.write('<strong>'+write +'</strong> '+end+' '+event)
}
daysTill();
</script>
if someone know, please help me. Thanks ♥
The getTime() method returns the time in milliseconds so to convert it to days you divide that by 86400000 (1000 for seconds * 60 for minutes * 60 for hours * 24 for days):
var relationship = new Date("2016/12/08");
var today = new Date();
var days = Math.ceil((today.getTime() - relationship.getTime()) / 86400000);
document.write(days + " days have pass since the start of the relationship.");
Try to use "JavaScript date maths"
// new Date(year, month (0-11!), day, hours, minutes, seconds, milliseconds);
var dateFuture = new Date(2017, 3, 1, 9, 0, 0, 0);
var dateLongAgo = new Date(2001, 8, 11, 8, 46, 0, 0);
var dateNow = new Date();
//86400000 millis per day
//floor --> all unter a full day shall be 'no day'
var daysSince = Math.floor((dateNow-dateLongAgo)/86400000);
var daysUntil = Math.floor((dateFuture-dateNow)/86400000);
console.log("long ago\t", dateLongAgo);
console.log("now is\t\t",dateNow);
console.log("then\t\t",dateFuture);
console.log("days since\t",daysSince);
console.log("days until\t", daysUntil);
If you don't mind using external libraries, Carbon is a nice tool extending DateTime
http://carbon.nesbot.com/docs/
It returns many kinds very nicely formatted dates -- months, days, hours etc included.

Pikaday date range don't work

I used the range function from pikaday.
with onSelectI set the date range what actually works.
Here is my example:
onSelect: function(date) {
var first_ = (date.getDate() - date.getDay())+1;
var last_ = first_ + 4;
var firstday = new Date(date.setDate(first_));
var lastday = new Date(date.setDate(last_));
picker.setStartRange(firstday);
picker.setEndRange(lastday);
picker.draw();
var f_startdate = firstday.getDate()+'.'+(firstday.getMonth()+1)+'.'+firstday.getFullYear();
var f_enddate = lastday.getDate()+'.'+(lastday.getMonth()+1)+'.'+lastday.getFullYear();
var kw = getWeekNumber(date.getFullYear()+'/'+(date.getMonth()+1)+'/'+date.getDate());
document.getElementById('calendar').value = f_startdate+' - '+f_enddate;
// document.getElementById('calendar').value = 'KW: '+(kw+1);
}
But when I select the 03.06.2016 the range is set to the "30.05.2016 - 03.05.2016" and the Input is wrong. Maybe anyone can help me.
Here is a working example: https://jsfiddle.net/24aL9f21/1/
Your issue is here:
var first_ = (date.getDate() - date.getDay())+1;
That gives you the date of the previous Monday, but also goes negative. 3 June is a Friday (day number 5), so first_ is set to:
3 - 5 + 1 = -1
Then:
var last_ = first_ + 4;
so last_ is set to 3. Now when you do:
var firstday = new Date(date.setDate(first_));
you are actually setting date to a date of -1, which is one before the start of the month so 30 May. setDate returns the time value, so firstday is a new Date instance set to 30 May also.
Then:
var lastday = new Date(date.setDate(last_));
you are setting date to 3 May (remembering that in the line above you set it to 30 May). Again, the setDate method returns the time value, so a new Date object is created for that date. So you get dates for 30 May and 3 May (and if you check date, you'll set it's also 3 May).
QED (which my Mathematics teacher told me was "Quite Easily Done"). ;-)
So your code for the Monday is fine. If you want to get the date for the following Friday, just do:
var lastday = date.setDate(date.getDate() + 4);
Here lastday and date will reference the same Date object, but creating another copy doesn't seem useful.

Determining time elapsed between 2 dates

I am trying to determine the time elapsed between 2 dates using javascript. An example would be: "I quit smoking on January 5, 2008 at 3 A.M., how many years, months, and hours has elapsed since I quit?".
So my thoughts were:
Get "quit" date
Get current date
Convert to time (milliseconds)
Find the difference
Create a new date using the difference
Extract the years, months, etc. from that date
Well, it is acting strange and I can't pin point why. Any insight?
//create custom test date
var d1 = new Date(2012, 8, 28, 13, 14, 0, 0);
//create current date
var d2 = new Date();
//get date times (ms)
var d1Time = (d1.getTime());
var d2Time = (d2.getTime());
//calculate the difference in date times
var diff = d2 - d1;
//create a new date using the time differences (starts at Jan 1, 1970)
var dDiff = new Date();
dDiff.setTime(diff);
//chop off 1970 and get year, month, day, and hour
var years = dDiff.getFullYear() - 1970;
var months = dDiff.getMonth();
var days = dDiff.getDate();
var hours = dDiff.getHours();
You can see it in action at this temporary host.
Why don't you just do the math to calculate the values? What you are putting into Date when you do dDiff.setTime(diff); is meaningless to you. That is just going to give you the date diff ms from the epoch.
Changing part of your code may solve your problem. jsfiddle
var start = new Date(0); // pivote point of date.
var years = dDiff.getFullYear() - start.getFullYear();
var months = dDiff.getMonth() - start.getMonth();
var days = dDiff.getDate() - start.getDate();
var hours = dDiff.getHours() - start.getHours();;
console.log(years, months, days, hours);​
But you have to manipulate these values based on there value( they may come negative).
Date represents a particular point in time, not a timespan between two dates.
You are creating a new date by setting dDiff milliseconds ellapsed since the unix epoch.
Once you have the milliseconds ellapsed, you should extract the information you need by dividing it. See this question.
May I recomend taking a look at Moment.js?
This won't be accurate as it does not take into account the leap dayys. Other than that, it is working correctly and I don't see any problem. The time difference is roughly 6.5 days. Taking into account timezone and the fact that 0 is Jan 1st, the value I see is as expected.
The accurate solution would be to
Convert the time difference into days
Subtract the number of leap years elapsed since the specified date
Divide the remaining by 365 to get the number of days
Create an array with the day count of each month (without considering leap days) and loop through the elapsed months, subtracting the day count for the completed months. The number of iterations will be your month count
The remainder is your day count
Various notes:
new Date(2012, 8, 28, 13, 14, 0, 0); is 28 September 2012 13:14:00 (not August if you would it)
new Date(0) returned value is not a constant, because of the practice of using Daylight Saving Time.
dDiff.getMonth(); return 0 for Jan, 1 for Feb etc.
The begin of date (1 Jan 1970) begin with 1 so in difference you should subtract this.
I think the second point is your mistake.
According with your algorithm, try this:
// create date in UTC
//create custom test date
var dlocaltime = new Date(2012, 8, 28, 13, 14, 0, 0);
var d1 = new Date(dlocaltime.getUTCFullYear(),dlocaltime.getUTCMonth(), dlocaltime.getUTCDate(), dlocaltime.getUTCHours(),dlocaltime.getUTCMinutes(),dlocaltime.getUTCSeconds());
//create current date
var now = new Date();
var d2 = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
console.log(d1);
console.log(d2);
//get date times (ms)
var d1Time = (d1.getTime());
var d2Time = (d2.getTime());
//calculate the difference in date times
var diff = d2 - d1;
//create a new date using the time differences (starts at Jan 1, 1970)
var dDiff = new Date();
dDiff.setTime(diff);
//chop off 1970 and get year, month, day, and hour
var years = dDiff.getUTCFullYear() - 1970;
var months = dDiff.getUTCMonth();
var days = dDiff.getUTCDate()-1; // the date of new Date(0) begin with 1
var hours = dDiff.getUTCHours();
var minutes = dDiff.getUTCMinutes();
var seconds = dDiff.getUTCSeconds();
console.log("Years:"+years);
console.log("months:"+months);
console.log("days:"+days);
console.log("hours:"+hours);
console.log("minutes:"+minutes);
console.log("seconds:"+seconds);

How to calculate ms since midnight in Javascript

What is the best way to calculate the time passed since (last) midnight in ms?
Create a new date using the current day/month/year, and get the difference.
var now = new Date(),
then = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
0,0,0),
diff = now.getTime() - then.getTime(); // difference in milliseconds
A bunch of answers so here another:
var d = new Date(), e = new Date(d);
var msSinceMidnight = e - d.setHours(0,0,0,0);
As a function:
function getMsSinceMidnight(d) {
var e = new Date(d);
return d - e.setHours(0,0,0,0);
}
alert(getMsSinceMidnight(new Date()));
Many answers except RobG's (recommended answer), Kolink's and Lai's are wrong here
Let's look closer together
First mistake
OptimusCrime and Andrew D. answers:
As Mala sugested, if the daylight saving correction was applied the nearest midnight, we get incorrect value. Let's debug:
Suppose it's last Sunday of March
The time is fixed at 2 am.
If we see 10 am on the clock, there's actually 11 hours passed from midnight
But instead we count 10 * 60 * 60 * 1000 ms
The trick is played when midnight happens in different DST state then current
Second mistake
kennebeck's answer:
As RobG wrote, the clock can tick if you get the system time twice. We can even appear in different dates sometimes. You can reproduce this in a loop:
for (var i = 0; true; i++) {
if ((new Date()).getTime() - (new Date()).getTime()) {
alert(i); // console.log(i); // for me it's about a 1000
break;
}
}
Third is my personal pitfall you could possibly experience
Consider the following code:
var d = new Date(),
msSinceMidnight = d - d.setHours(0,0,0,0);
msSinceMidnight is always 0 as the object is changed during computation before the substraction operation
At last, this code works:
var d = new Date(),
msSinceMidnight = d.getTime() - d.setHours(0,0,0,0);
Simpler to write, if you don't mind creating two dates.
var msSinceMidnight= new Date()-new Date().setHours(0,0,0,0);
var d=new Date();
// offset from midnight in Greenwich timezone
var msFromMidnightInGMT=d%86400000;
// offset from midnight in locale timezone
var msFromMidnightLocale=(d.getTime()-d.getTimezoneOffset()*60000)%86400000;
var today = new Date();
var d = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0);
var difference = today.getTime() - d.getTime();
Seconds since midnight would simply be to display the time, but instead of using hours:minutes:seconds, everything is converted into seconds.
I think this should do it:
var now = new Date();
var hours = now.getHours()*(60*60);
var minutes = now.getMinutes()*60;
var seconds = now.getSeconds();
var secSinceMidnight = hours+minutes+seconds;

Categories