Adding Day to Date to Make Current Date Tomorrow - Javascript [duplicate] - javascript

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 8 years ago.
Hi Everyone and thanks in advance for the help. I'm having an issue with getting my Javascript date code to advance from the current date to tomorrow's date. I've searched here in previous posts but the answers don't seem to be working.
<SCRIPT LANGUAGE="JavaScript">
// Get today's current date.
var now = new Date();
// Array list of days.
var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
// Array list of months.
var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
// Calculate the number of the current day in the week.
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
// Calculate four digit year.
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;
}
// Join it all together
today = days[now.getDay()] + ", " +
months[now.getMonth()] + " " +
date + ", " +
(fourdigits(now.getYear())) ;
</script>
Where would the + 1 be inserted in order to make the date tomorrow's date?

now.setDate(now.getDate() + daysToAdd);
should do the trick. It's not even jQuery, just Javascript. If you're getting the 1 added to the end of the string make sure now is still being treated as a Date and hasn't been reassigned somewhere to a different type.
It shouldn't matter whether daysToAdd is a literal or a variable, either. Both should work.
More specifically, this should work:
<SCRIPT LANGUAGE="JavaScript">
// Get today's current date.
var now = new Date();
now.setDate(now.getDate() + 1);
// Array list of days.
var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
// Array list of months.
var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
// Calculate the number of the current day in the week.
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
// Calculate four digit year.
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;
}
// Join it all together
today = days[now.getDay()] + ", " +
months[now.getMonth()] + " " +
date + ", " +
(fourdigits(now.getYear())) ;
</script>

Related

Add 1 month to current date in JavaScript (Can you please integrate your solution/answer to this code and show) [duplicate]

This question already has answers here:
How to add months to a date in JavaScript? [duplicate]
(3 answers)
Closed 2 years ago.
$(document).ready(function () {
//Init
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
$('#PaymentDate').val(today);
});
I'm new to JavaScript So can someone help me. using this code I can get the current date...But, how can I add one month to this date and get the next month date..
Currently I'm getting this - 12/30/2020 (Today's Date) Add 1 month Means I want to get - 01/30/2021 (Next month date).
Can you please integrate your solution/answer to this code and show
Try this
$(document).ready(function () {
//Init
var now = new Date();
// Add one month to the current date
var next_month = new Date(now.setMonth(now.getMonth() + 1));
// Manual date formatting
var day = ("0" + next_month.getDate()).slice(-2);
var month = ("0" + (next_month.getMonth() + 1)).slice(-2);
var next_month_string = next_month.getFullYear() + "-" + (month) + "-" + (day);
$('#PaymentDate').val(next_month_string);
});
You can also use this trick to get your YYYY-MM-DD style string instead of the manual formatting:
var next_month_string = next_month.toISOString().split('T')[0];

displaying the day of the week 3 days before today's date using javascript

I tried this javascript to display the day of the week from 3 days before the html page is accessed. It doesn't work when today is Sunday, Monday or Tuesday.
(I think the problem is that the days are numbered 0-6 with no consideration of negative numbers in the line var date)
var now = new Date();
var days = new Array(
'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
var months = new Array(
'January','February','March','April','May',
'June','July','August','September','October',
'November','December');
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate()-3;
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;}
today = days[now.getDay() -3] + ", " +
months[now.getMonth()] + " " +
date + ", " +
(fourdigits(now.getYear()));
document.write(today);
There are a number of issues with your code.
<SCRIPT LANGUAGE="JavaScript">
The language attribute for script elements was deprecated in HTML 4 and removed in subsequent versions.
<!--
HTML comment delimiters are tolerated at the start and end of script elements but should not be used. They have been unnecessary for 20 years.
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate()-3;
When the date is 1 to 3, the first part of the expression will return a string like "0" or "". The second part will return a number from -2 to 0, so the result will be "0-2" to "00".
You can do something like:
var date = now.getDate();
date = (date < 10? '0' : '') + date;
Then there is:
today = days[now.getDay() -3] + ", " +
getDay returns a number representing the day of the week, 0 for Sunday to 6 for Saturday, so from Sunday to Tuesday (day numbers 0–2) you'll be attempting to access a property of days that doesn't exist, which will return undefined.
(fourdigits(now.getYear()));
getYear always returns the year less 1900. Use getFullYear instead.
See Where can I find documentation on formatting a date in JavaScript? and Add +1 to current date.
You should start by subtracting 3 days from the date, then format the result for output:
var now = new Date();
now.setDate(now.getDate() - 3);
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday', 'Friday','Saturday'];
var months = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
var date = now.getDate();
date = (date < 10? "0" : "") + date;
var today = days[now.getDay()] + ", " +
months[now.getMonth()] + " " +
date + ", " + now.getFullYear();
document.write(today);

Javascript Concatenate dates and time together

I have this code which generates the current date + time in javascript:
var date_variable = new Date();
var year = date_variable.getFullYear();
var month = date_variable.getMonth() + 1;
var day = date_variable.getDate();
var hour = date_variable.getHours();
var minutes = date_variable.getMinutes();
var seconds = date_variable.getSeconds();
var full_date = year + month + day + hour + minutes + seconds;
console.log(year);
console.log(month);
console.log(day);
console.log(hour);
console.log(minutes);
console.log(seconds);
console.log(full_date);
Everything in console displays fine, except when it comes to the full_date variable. This is what's displayed in console:
2014
8
27
10
53
10
2122
My question is, why does the last output not combine my date + time into a single string?
Thanks
You need to concatenate the numbers with a string first.
var full_date = year +""+ month +""+ day +""+ hour +""+ minutes +""+ seconds;
Each of the properties you are accessing return a number. When you add them together with the + operator, you are just adding numbers together.
If you substitute the variables used in full date, it would look something like:
var full_date = 2014 + 8 + 26 + . . .
All you have to do is put a strings in the expression and you will get what you want.
In all honesty though, you should use Date.toLocalDateString() or Date.toLocalTimeString() if the format works for you. You can read the documentation about them on MDN's Date reference page.

getting the difference between two dates [duplicate]

This question already has answers here:
How do I get the difference between two Dates in JavaScript?
(18 answers)
Closed 9 years ago.
I'm working on an assignment where I must use Javascript. In my application a user types a date into a form. Then I try to compare that date with the current date. The difference is the number of days they have to complete a task. However, I'm having a bit of trouble when it comes to the calculations. dueDate is a paramater for an object dynamically created.
function getFormData() {
var adate = document.getElementById("dueDate").value;
if (checkInputText(dueDate, "Please enter a date")) return;
...
}
function processDate(adate) {
var splitArray = adate.split("-");
var year = splitArray[0];
var month = splitArray[1] - 1;
var day = splitArray[2];
var date = new Date(year, month, day);
var dateParse = date.getTime();
return dateParse;
}
function compareDates(dueDate) { //dueDate is the value from the form
var cdate = new Date();
console.log("this is todays date" + " " + cdate); //shows correct date
var cdateparse = Date.parse(cdate);
var dueDateparse = Date.parse(dueDate);
var diff = dueDateparse - cdateparse;
var daysCal = diff / 1000 / 60 / 60 / 24;
var days = parseInt(daysCal); //where I'm having trouble
console.log(days);
if (days == 0) {
mymessage = " you have to do this task today";
}
try {
if (days < 0) {
mymessage = "this task is overdue by" + " " + -days + " " + "days";
throw new Error("you are overdue");
}
} catch (ex) {
alert(ex.message);
return;
}
if (days > 0) {
console.log("the difference is greater than 0");
mymessage = "you have" + " " + days + " " + "more days";
}
}
The issue happens when I put in the current date into the form. I've tried math.floor and math.round but the number is always rounded up and throws my message, saying that the task is overdue. Using parseInt has brought me closest to my desired outcome, but when I put in tomorrow's date it says that I am overdue. Any suggestions?
http://jsfiddle.net/sujesharukil/QspFj/
use
var days = Math.ceil(daysCal);
instead of parseInt.
You should beware of that new Date(year, month, day); creates a timestamp for 0:00 AM.
So everything that happens on that day, will already have a negative diff (> -1, though). So you should use Math.ceil instead of rounding. Or you set the deadline to 23:59:59 (i.e. just increase the day by 1).

How to calculate years and months between two dates in Javascript?

Is there a way to calculate the count of years (considering leap years also) and months between two different dates in Javascript?
Here is the best way I know to get years and months:
// Assumes Date From (df) and Date To (dt) are valid etc...
var df= new Date("01/15/2010");
var dt = new Date("02/01/2012");
var allMonths= dt.getMonth() - df.getMonth() + (12 * (dt.getFullYear() - df.getFullYear()));
var allYears= dt.getFullYear() - df.getFullYear();
var partialMonths = dt.getMonth() - df.getMonth();
if (partialMonths < 0) {
allYears--;
partialMonths = partialMonths + 12;
}
var total = allYears + " years and " + partialMonths + " months between the dates.";
var totalMonths = "A total of " + allMonths + " between the dates.";
console.log(total);
console.log(totalMonths);
return {jaren: allYears, maanden: partialMonths};
This might be a helpful source:
http://www.merlyn.demon.co.uk/js-date1.htm#DYMD
The following snippet contains my solution. It's based on the idea that a currentDate - pastDate already is the result.
If you don't want negative results, you have to check that years and month is not less than 0.
const pastDate = '1989-02-10'
const period = new Date(new Date().getTime() - new Date(pastDate).getTime())
const years = period.getFullYear() - 1970 // at 1970 the date calendar starts
const months = period.getMonth()
console.log('years: ', years, ', month: ', months)
You will find a complete javascript function here with validation.
Edit: Link is dead - here is a simple JS line that calculates the difference in months between two dates:
return dateTo.getMonth() - dateFrom.getMonth() +
(12 * (dateTo.getFullYear() - dateFrom.getFullYear()));
That is assuming that you have the dates in two variables called dateTo and dateFrom.
Have a look at the JavaScript Date object.

Categories

Resources