Create date object and compare to todays date - javascript

I have an object containing time. For example x.time = 10:20:00.
I want to take the current time minus my objects time.
This is my code so far, but i get the error message ="Invalid Date":
for(var i = 0; i<x.length; i++){
nowDate = new Date();
minutesLeft = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() + x[i].time);
text +- "It is "+ minutesLeft[i] + " milliseconds left";
}

In order to convert your time property into a date object you can do:
var timepieces = x.time.split(':');
var date = new Date();
date.setHours(timepieces[0]);
date.setMinutes(timepieces[1]);
date.setSeconds(timepieces[2]);
Then you can directly compare the two dates by using the getTime() method of the Date object.
nowDate.getTime() === date.getTime()
nowDate.getTime() > date.getTime()
nowDate.getTime() < date.getTime()
You can also get the difference of two dates in milliseconds:
var milliseconds = nowDate.getTime() - date.getTime();

There are a bunch of problems with your code. I'll go through and hopefully catch everything.
Use var to declare your variables inside your loop. (further reading)
When you create the variable minutesLeft you are doing a bit of weird concatenation. You told us that x.time is a string such as "10:20:00" but you are (string) concatenating that with Date.prototype.getDate which returns a number in the range 1-31 (representing the day of the month). You are essentially doing this:
minutesLeft = new Date(2017,0,1910:20:00);
Which I hope you see will not create a new date. You perhaps wanted something along the lines of
minutesLeft = new Date(2017,0,19, 10, 20, 0);
Which should give you what you want (todays date set to the appropriate time defined by x.time.
text +- does not make any sense. I suspect a typo, you meant text += which will append the value on the right to the variable text. Or, perhaps text = which will assign the value, replacing what was there
"It is "+ minutesLeft[i] + " milliseconds left" using minutesLeft[i] will take a single character from a string (or an item from an array, if the value is an array). Yours is just a date object, and is not an array, so I suspect you just meant to leave off the [i] part altogether.
If you're trying to get the difference between the current date/time and your selected date/time you need to do some arithmetic with nowDate and minutesLeft. I'm assuming this is a difference you're after.
var x = [{time:"10:20:20"}];
var text = "";
for(var i = 0; i<x.length; i++){
var nowDate = new Date();
var timeSplit = x[i].time.split(":");
var minutesLeft = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate());
minutesLeft.setHours(timeSplit[0]);
minutesLeft.setMinutes(timeSplit[1]);
minutesLeft.setSeconds(timeSplit[2]);
text += "It is "+ (nowDate-minutesLeft) + " milliseconds left";
}
console.log(text);

For example x.time = 10:20:00. I want to take the current time minus my objects time.
Your code seems quite confused, it seems you're trying to do the following:
var time = '10:20:00';
var timeParts = time.split(':');
var now = new Date();
// Current date and time
console.log(now.toString());
// Subtract the hours part of the time from the hours part of the current time
now.setHours(now.getHours() - timeParts[0]);
// Subtract the minutes part of the time from the minutes part of the current time
now.setMinutes(now.getMinutes() - timeParts[1]);
// Subtract the seconds part of the time from the seconds part of the current time
now.setSeconds(now.getSeconds() - timeParts[2]);
// Adjusted date and time
console.log(now.toString());
// You can set the time parts all in one go:
var now2 = new Date();
now2.setHours(now2.getHours() - timeParts[0],
now2.getMinutes() - timeParts[1],
now2.getSeconds() - timeParts[2]);
console.log(now2.toString());
Lastly, copying a date is as simple as:
var date1 = new Date();
var date2 = new Date(date1);

Related

Increment Date Object in without converting to epoch in Javascript

Is it possible to increment a date object by one day without converting the object to an epoch number?
For example the traditional way will convert the date object to an epoch number:
var today = new Date();
var tomorrow = new Date(today.valueOf()); // copy date object without converting to epoch
tomorrow.setDate(tomorrow.getDate() + 1); // now gets converted to epoch :'(
The set* methods don't "convert to epoch number", they modify the date's internal time value and return the modified value. The date object is still a date.
let today = new Date();
today.setHours(0,0,0,0); // Start of day
let tvToday = +today;
let tomorrow = new Date(today);
// setDate adjusts the time value and returns it
let tvTomorrow = tomorrow.setDate(tomorrow.getDate() + 1);
console.log('Today\'s date: ' + today.toDateString());
console.log('Today\'s time value: ' + tvToday);
console.log('Tomorrow\'s date: ' + tomorrow.toDateString());
console.log('Tomorrow\'s time value: ' + tvTomorrow);
// May vary from 24 by up to 1 hour depending on crossing DST boundaries
console.log('Difference in hours: ' + ((tvTomorrow - tvToday)/3.6e6));
If you want a method that adds a day and returns a new Date object, write a function, maybe named addDays, that takes a date and number of days to add and returns a new Date object with the days added. Lots of libraries have such functions, they're not hard to write.
Not sure if you can do that without converting. Maybe convert back after.
var today = new Date();
var tomorrow = new Date(today.valueOf());
const x = tomorrow.setDate(tomorrow.getDate() + 1);
console.log(x) //epoch
const z = new Date(x)
console.log(z.toString())

How to add 31 days to a date inputted by the user

So I'm trying to make a period counter (cliche) and I'm also beginner at HTML and Javascript so bear with me. I made it so the user can put in the date that their period started, and I want to add 31 to the amount of days they entered so it comes out as a date.
My script so far:
function theDate() {
var m = document.getElementById("inmonth").value;
Number(m).toString();
var d = document.getElementById("inday").value;
var y = document.getElementById("inyear").value;
var nd = new Date(m + "/" + d + "/" + y);
var thirtyDaysLater = 31;
var fstart = nd.setDate(nd.getDate() + thirtyDaysLater);
document.getElementById("enddate").innerHTML = "Last Period End Date: " +
nd;
document.getElementById("nextdate").innerHTML = "Next Period Start Date: " +
fstart;
definitely a duplicate but setDate both returns a number (the number of seconds since X passed) and modifies the date, so you'd want to do something like this.
// After setting nd and thirty days later
var fstart = new Date(nd); //copy the date
fstart.setDate(fstart.getDate() + thirtyDaysLater);
// Now fstart contains the modified date and nd contains the initial one.
From there just use as you want.
In short
var a = new Date(b) // date Object a copy of b
a.setDate(num) // Returns a number (which identifies the date) and modifies a
b = new Date(a.setDate(num)) // a is modified, b is now a copy of a.
and for funsies
// a contains the current date - 30 days (it properly accounts for months)
var a = new Date(new Date().setDate(new Date().getDate() - 30));
You should not use the built-in parser. Rather then building a string, giving it to an unreliable parser and hoping you get a consistent result, just give the parts directly to the Date constructor.
Also, setDate modifies the date in place, so there's no need for fstart:
function theDate() {
var y = document.getElementById("inyear").value;
var m = document.getElementById("inmonth").value;
var d = document.getElementById("inday").value;
var nd = new Date(y, m-1, d);
document.getElementById("enddate").innerHTML = "Last Period End Date: " + nd.toString();
var thirtyDaysLater = 31;
nd.setDate(nd.getDate() + thirtyDaysLater);
document.getElementById("nextdate").innerHTML = "Next Period Start Date: " + nd.toString();
}
Day: <input id="inday" value="5"><br>
Month: <input id="inmonth" value="10"><br>
Year: <input id="inyear" value="2017"><br>
<button onclick="theDate()">Calculate</button>
<p id="enddate">
<p id="nextdate">
This doesn't do any validation of input, you may want to add that.

Show all date between two date range in javascript

I want to show all dates between two days.I can't do this.Please help..
This is my code...
var Day = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date("2017-04-10");
var secondDate = new Date("2017-04-15");
var diffDays = (secondDate.getTime() - firstDate.getTime())/Day;
alert(diffDays);
for(var i=0;i<= diffDays ;i++)
{
var d = new Date(firstDate + i);
alert(d);
}
Your i variable is the number of the day to display. Your firstDate variable is a Date.
This line:
var d = new Date(firstDate + i);
adds these together and tries to create a new Date. Due to these being different types (a date and a number) type coercion comes into play (ie: the Date and the Number get converted to strings, and concatenated together).
Try this:
var DAY_IN_MS = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var theDate = new Date("2017-04-10");
var i = 5;
// Date + Number = Type Coercion! Both objects will be converted to strings and concatenated together.
alert(theDate + i);
// The Date constructor doesn't care, and will work because it can get a date from the first part of the string.
alert(new Date(theDate + i));
// If you use `getTime()` you can get the numerical value of the Date, which you can use for arithmetic.
alert(theDate.getTime());
// By adding `i`, however, you are only adding a few milliseconds to the first date !!
alert(new Date(theDate.getTime() + i);
// Number + Number of days times milliseconds per day = success!
alert(new Date(theDate.getTime() + (i * DAY_IN_MS)));
I think you mean:
var d = new Date(firstDate.getTime() + (i * Day));
Short answer, increment the right amount of milliseconds to firstDate.getTime() :
for(var i=0;i<= diffDays ;i++)
{
firstDate = new Date(firstDate.getTime() + Day);
console.log(firstDate);
}
Long answer, you have several things wrong in your code :
Here var d = new Date(firstDate + i); you are adding to a Date object string representation the value of i in this case incremented on the loop.
You are then parsing this String into a new Date object, but Javascript only recognizes the date and ignores the appended number
You should either try to get the milliseconds of firstDate as you did for diffDays and then add i * Day (also consider renaming this variable to something else, maybe a const DAY_IN_MS or something).

JavaScript: Parse time string and add minutes to it

$.getJSON("api/times", function(times) {
var time1 = times.departure; // 14:36:30 (string)
var minutesToAdd = parseInt(times.minutesToAdd); // 6
var total = "?"; // How can I add minutesToAdd to time1?
});
I am trying to parse time1 so that I can add the minutesToAdd value to the time. The time1 value comes directly from a MySQL database. It is obtained through an API that returns this data in JSON. How can I do this?
I think you can try this
on line 1 : You have to add a demo date with the time in javascript so that you can create the date object. Later you can do date.getTime() to get the time in milisecond.
var newDateObj = new Date("01/01/13 14:36:30"); // '01/01/13' is the demo value
alert(newDateObj)
var date = new Date(newDateObj.getTime() + 5*60000);
alert(date) // date.getTime() will give you the time
I you don't want to use Date, use split to get the three parts of your time string. Then you just add your minutes and make sure you don't exceed 59 minutes (if you think it is useful, check if hours doesn't exceed 23) :
$.getJSON("api/times", function(times) {
var time1 = times.departure; // 14:36:30 (string)
var minutesToAdd = parseInt(times.minutesToAdd);
var time = time1.split(':');
var time[1] += minutesToAdd;
if (time[1] >= 60) {
time[1] = 0;
time[0]++; // maybe you should test if >= 24
}
var total = time.join(':'); // equivalent to "time[0]+':'+time[1]+':'+time[2]"
});`

javascript date subtraction

I am looking for a way to do proper subtraction between two javascript Date objects and get the day delta.
This is my approach but it fails for todays date as an input:
<script type="text/javascript">
function getDayDelta(incomingYear,incomingMonth,incomingDay){
var incomingDate = new Date(incomingYear,incomingMonth,incomingDay);
var today = new Date();
var delta = incomingDate - today;
var resultDate = new Date(delta);
return resultDate.getDate();
}
//works for the future dates:
alert(getDayDelta(2009,9,10));
alert(getDayDelta(2009,8,19));
//fails for the today as input, as expected 0 delta,instead gives 31:
alert(getDayDelta(2009,8,18));
</script>
What would be a better approach for this ?
The month number in the Date constructor function is zero based, you should substract one, and I think that is simplier to calculate the delta using the timestamp:
function getDayDelta(incomingYear,incomingMonth,incomingDay){
var incomingDate = new Date(incomingYear,incomingMonth-1,incomingDay),
today = new Date(), delta;
// EDIT: Set time portion of date to 0:00:00.000
// to match time portion of 'incomingDate'
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
// Remove the time offset of the current date
today.setHours(0);
today.setMinutes(0);
delta = incomingDate - today;
return Math.round(delta / 1000 / 60 / 60/ 24);
}
getDayDelta(2008,8,18); // -365
getDayDelta(2009,8,18); // 0
getDayDelta(2009,9,18); // 31
(2009,8,18) is NOT August 18th. It's September 18th.
You could call getTime() on each date object, then subtract the later from the earlier. This would give you the number of milliseconds difference between the two objects. From there, it's easy to get to days.
A couple of hiccups to watch for, though: 1) daylight savings time, and 2) ensuring your times are coming from the same time zone.
This will work better, but it doesn't properly deal with negative result values. You might want to simply parse the values yourself and deal with them.
function getDayDelta(incomingYear,incomingMonth,incomingDay){
var incomingDate = new Date(incomingYear,incomingMonth-1,incomingDay);
var today = new Date();
today = new Date(Date.parse(today.format("yyyy/MM/dd")));
var delta = incomingDate - today;
if (delta == 0) { return 0; }
var resultDate = new Date(delta);
return resultDate.getDate();
}
//works for the future dates:
alert(getDayDelta(2009,9,10));
alert(getDayDelta(2009,8,19));
alert(getDayDelta(2009, 8, 18));

Categories