JavaScript, get date of the next day [duplicate] - javascript

This question already has answers here:
Incrementing a date in JavaScript
(19 answers)
Closed 8 years ago.
I have the following script which returns the next day:
function today(i)
{
var today = new Date();
var dd = today.getDate()+1;
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
today = dd+'/'+mm+'/'+yyyy;
return today;
}
By using this:
today.getDate()+1;
I am getting the next day of the month (for example today would get 16).
My problem is that this could be on the last day of the month, and therefore end up returning 32/4/2014
Is there a way I can get the guaranteed correct date for the next day?

You can use:
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate()+1);
For example, since there are 30 days in April, the following code will output May 1:
var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000
var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000
See fiddle.

Copy-pasted from here:
Incrementing a date in JavaScript
Three options for you:
Using just JavaScript's Date object (no libraries):
var today = new Date();
var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
One-liner
const tomorrow = new Date(new Date().getTime() + (24 * 60 * 60 * 1000));
Or if you don't mind changing the date in place (rather than creating
a new date):
var dt = new Date();
dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));
Edit: See also Jigar's answer and David's comment below: var tomorrow
= new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
Using MomentJS:
var today = moment();
var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than
returning a new instance, so today.add(1, 'days') would modify today.
That's why we start with a cloning op on var tomorrow = ....)
Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();

Using Date object guarantees that. For eg if you try to create April 31st :
new Date(2014,3,31) // Thu May 01 2014 00:00:00
Please note that it's zero indexed, so Jan. is 0, Feb. is 1 etc.

Related

How to get the difference between 2 dates excluding weekends (Sun, and Sat) in Javascript? [duplicate]

This question already has answers here:
exclude weekends in javascript date calculation
(6 answers)
Closed 6 years ago.
very quick question.
I have a datetime stored in my sql database. I am using this date to calculate the difference in time between those datetimes like the following:
var date1 = new Date(request[0].RequestDate.toString()); //coming from my db
var date2 = new Date(); // current datetime
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // calc diff
var rod= timeDiff / (1000 * 3600 * 24);
rod= rod.toFixed(2); // result that I want
However, this will give me the difference between those 2 dates including Sat and Sun.. How can I change my JS code to exclude Sat and Sun.
PS note: the day in the database that I am dealing with has, for example, the following format: Mon Dec 12 2016 10:23:50 GMT-0500 (Eastern Standard Time) and I need the diff in "time" as you can notice in my JS code.
Thanks!
A simple for loop going through the total days, creating a date object for that day and incrementing a new days total count should do it:
var days = 0;
for (d = 0; d <= rod; d++) {
var thisDate = new Date(
date1.getYear(),
date1.getMonth(),
(date1.getDate()+d),
date1.getHours(),
date1.getMinutes(),
date1.getSeconds()
);
// 0: Sunday, 6: Saturday
if (thisDate.getDay() > 0 &&
thisDate.getDay() < 6) {
days++;
}
}
days.toFixed(2);
To now get the date differences from that in time, you only need to construct a new date from the start date using the new total number of days you have from the above:
var startDate = new Date(date1.toDateString());
date1.setDate(date1.getDate() + days);
var endDate = new Date(date1.toDateString());

Today's date -30 days in JavaScript

I need to get today's date -30 days but in the format of: "2016-06-08"
I have tried setDate(date.getDate() - 30); for -30 days.
I have tried date.toISOString().split('T')[0] for the format.
Both work, but somehow cannot be used together.
setDate() doesn't return a Date object, it returns the number of milliseconds since 1 January 1970 00:00:00 UTC. You need separate calls:
var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2016-06-08"
You're saying that those two lines worked for you and your problem is combining them. Here is how you do that:
var date = new Date();
date.setDate(date.getDate() - 30);
document.getElementById("result").innerHTML = date.toISOString().split('T')[0];
<div id="result"></div>
If you really want to subtract exactly 30 days, then this code is fine, but if you want to subtract a month, then obviously this code doesn't work and it's better to use a library like moment.js as other have suggested than trying to implement it by yourself.
Please note that you would be better to use something like moment.js for this rather than reinventing the wheel. However a straight JS solution without libraries is something like:
var date = new Date();
date.setDate(date.getDate() - 30);
sets date to 30 days ago. (JS automatically accounts for leap years and rolling over months less than 30 days, and into the previous year)
now just output it like you want (gives you more control over the output). Note we are prepending a '0' so that numbers less than 10 are 0 prefixed
var dateString = date.getFullYear() + '-' + ("0" + (date.getMonth() + 1)).slice(-2) + '-' + ("0" + date.getDate()).slice(-2)
// Format date object into a YYYY-MM-DD string
const formatDate = (date) => (date.toISOString().split('T')[0]);
const currentDate = new Date();
// Values in milliseconds
const currentDateInMs = currentDate.valueOf();
const ThirtyDaysInMs = 1000 * 60 * 60 * 24 * 30;
const calculatedDate = new Date(currentDateInMs - ThirtyDaysInMs);
console.log(formatDate(currentDate));
console.log(formatDate(calculatedDate));
Today's date -30 days in this format: "YYYY-MM-DD":
var date = new Date();
date.setDate(date.getDate() - 30);
var dateString = date.toISOString().split('T')[0]; // "2021-02-05"
Today's date -30 days but get all days in this format: "YYYY-MM-DD":
var daysDate = [];
for(var i = 1; i<= 30; i++) {
var date = new Date();
date.setDate(date.getDate() - i);
daysDate.push(date.toISOString().split('T')[0]); // ["2021-02-05", "2021-02-04", ...]
}
Simply you can calculate in terms of timestamp
var date = new Date(); // Current date
console.log(date.toDateString())
var pre_date = new Date(date.getTime() - 30*24*60*60*1000);
// You will get the Date object 30 days earlier to current date.
console.log(pre_date.toDateString())
Here 30*24*60*60*1000 refers to time difference in miliseconds.

Decrement the date by one day using javascript for loop?

$(document).ready(function() {
var date = new Date();
var data_new = [];var url ='http://www.domain.com /kjdshlka/api.php?date=2014-07-15';
$.getJSON(url,function(result) {
var elt = [date,result.requests];data_new.push(elt);console.log(data_new);
});
});
I am struggling to decrement the date by one day using javascript for loop.Here is my code,from the url im getting some requests.like if i decrease the date by one day other requests will come .Now i need this process for 7days using javascript for loop.Can anybody please tel me how to do ?
var date = new Date(); // Date you want, here I got the current date and time
date.setDate(date.getDate()-1);
getDate() will give you the date, then reduce it by 1 and using setDate() you can replace date again.
var today = new Date();
var yesterday = new Date(today.getTime() - (24 * 60 * 60 * 1000)); //(hours * minutes * seconds * milliseconds)
console.log(yesterday);
var now = new Date();
console.log(now);
var yesterday = new Date(now - 86400000);
console.log(yesterday);
/* In a Decrement Loop*/
for(var i=100;i>0;i--){
console.log(new Date(now - i*86400000));
}

Comparing two dates in JavaScript

I am currently trying to compare the launch_date with today's date. Let's say if the launch_date is within 3 years from today's date, it should perform something but I only managed to come out with some portion of the code:
var today = new Date();
var launch_date = 2011/10/17 00:00:00 UTC;
//if today's date minus launch_date is within 3 years, then do something.
Any guides? Thanks in advance.
To explicitly check for the three year range
var ld = new Date('2011/10/17 00:00:00 UTC')
if(today.getFullYear() - ld.getFullYear() < 3) {
//do something
}
This will fail on an invalid date string and possibly some other edge cases.
If you'll be doing a lot of date calculations I highly recommend Moment: http://momentjs.com/
you could always calculate the timespan in days and use that.
var getDays = function(startDate, endDate){
var ONE_DAY = 1000 * 60 * 60 * 24;
var difference = endDate.getTime() - startDate.getTime();
return Math.round(difference / ONE_DAY);
}
See this JsFiddle: http://jsfiddle.net/bj4Dq/1/
Try-
var today = new Date();
var launch_date = new Date("2011/10/17 00:00:00 UTC");
var diff = today.getYear() - launch_date.getYear();
if(diff <=3 )
alert("yes");
else
alert("no");
jsFiddle
you can create a Date object and invoke getTime() method (returns numer of milliseconds since 1970-01-01). Use one of this rows:
var yourDate = new Date(dateString) // format yyyy-mm-dd hh:mm:ss
var yourDate = new Date(year, month, day, hours, minutes, seconds, milliseconds)
After in the if statement use this condition:
var edgeDate = // new Date(dateString);
if ( (today.getTime () - yourDate.getTime ()) >= edgeDate.getTime() ){
// do something
}
Regards,
Kevin

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