How to add weeks to date using javascript? - javascript

Javascript definitely isn't my strongest point. I've been attempting this for a couple of hours now and seem to be getting stuck with date formatting somewhere.
I have a form where a user selected a date (dd/mm/yyyy) and then this date will be taken and 2 weeks will be added to it and then date will be copied to another form field.
My latest attempt below isn't even adding a date yet just copying the selected date in one form field to another, if I select '03/02/2012', it outputs 'Fri Mar 02 2012 00:00:00 GMT+0000 (GMT Standard Time)', so its outputting in American format as well as the full date. How to I get it to out put in the same format and add 2 weeks?
function LicenceToOccupy(acceptCompletionDate)
{
var date1 = new Date(acceptCompletionDate);
document.frmAccept.acceptLicence.value = date1;
}

You can do this :
const numWeeks = 2;
const now = new Date();
now.setDate(now.getDate() + numWeeks * 7);
or as a function
const addWeeksToDate = (dateObj,numberOfWeeks) => {
dateObj.setDate(dateObj.getDate()+ numberOfWeeks * 7);
return dateObj;
}
const numberOfWeeks = 2
console.log(addWeeksToDate(new Date(), 2).toISOString());
You can see the fiddle here.
According to the documentation in MDN
The setDate() method sets the day of the Date object relative to the beginning of the currently set month.

This might not answer the question per se, but one can find a solution with these formulas.
6.048e+8 = 1 week in milliseconds
Date.now() = Now in milliseconds
Date.now() + 6.048e+8 = 1 week from today
Date.now() + (6.048e+8 * 2) = 2 weeks from today
new Date( Date.now() + (6.048e+8 * 2) ) = Date Object for 2 weeks from today

You're assigning date1 to be a Date object which represents the string you pass it. What you're seeing in the acceptLicense value is the toString() representation of the date object (try alert(date1.toString()) to see this).
To output as you want, you'll have to use string concatenation and the various Date methods.
var formattedDate = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
In terms of adding 2 weeks, you should add 14 days to the current date;
date1.setDate(date.getDate() + 14);
... this will automatically handle the month increase etc.
In the end, you'll end up with;
var date1 = new Date(acceptCompletionDate);
date1.setDate(date1.getDate() + 14);
document.frmAccept.acceptLicence.value = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
N.B Months in JavaScript are 0-indexed (Jan = 0, Dec = 11), hence the +1 on the month.
Edit: To address your comment, you should construct date as follows instead, as the Date argument is supposed to be "A string representing an RFC2822 or ISO 8601 date." (see here).
var segments = acceptCompletionDate.split("/");
var date1 = new Date(segments[2], segments[1], segments[0]);

This should do what you're looking for.
function LicenceToOccupy(acceptCompletionDate)
{
var date1 = new Date(acceptCompletionDate);
date1.setDate(date1.getDate() + 14);
document.frmAccept.acceptLicence.value = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
}

To parse the specific dd/mm/yyyy format and increment days with 14 , you can do something like split the parts, and create the date object with y/m/d given specfically. (incrementing the days right away) Providing the separator is always -, the following should work:
function LicenceToOccupy(acceptCompletionDate)
{
var parts = acceptCompletionDate.split("/");
var date1 = new Date(parts[2], (parts[1] - 1), parseInt(parts[0]) + 14); //month 0 based, day: parse to int and increment 14 (2 weeks)
document.frmAccept.acceptLicence.value = date1.toLocaleDateString(); //if the d/m/y format is the local string, otherwise some cusom formatting needs to be done
}

date1.toLocaleDateString()
Thiswill return you date1 as a String in the client convention
To create a new date date2 with 2 weeks more (2weeks = 27246060 seconds):
var date2 = new Date(date1 + 60*60*24*7*2);

Related

Remove time part from date in js

let date = invoice.due_date;
console.log(date);
Output 2019-06-13 00:00:00
d = date.split(' ')[0]; //didnt work for me
How can I remove the time and only have the date.
I just added .toLocaleDateString
The toLocaleDateString() method returns a string with a language-sensitive representation of the date portion of the date. The locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function.
let date = new Date("2019-06-13T02:00:00Z").toLocaleDateString()
console.log(date)
Reference:
toLocaleDateString
Another Example:
If you want to have a ISO Date try this one:
date = new Date('2019-06-13T02:00:00Z');
year = date.getFullYear();
month = date.getMonth() + 1;
dt = date.getDate();
if (dt < 10) {
dt = '0' + dt;
}
if (month < 10) {
month = '0' + month;
}
console.log(year + '-' + month + '-' + dt);
let date = invoice.due_date;
console.log(date.getDate() + '-' + (date.getMonth()+1) + '-' + date.getFullYear());
You can try this way. Can create any format like dd-MM-yyyy or anything.
Recommendation: Use moment library for date formatting.
If you had a string, the split would work.
It is either not a string (e.g. null) or something else not a string.
Your console.log shows a date string so it is obviously a Date object.
To get the second part in ANY case (space or with a T between the date and time) you need to get the ISOString to be able to PERSISTENTLY get the correct output.
Any toLocaleString or similar is implementation and locale dependent
let date = invoice.due_date.toISOString()
Like this:
// Assuming a date object because your console log and the split that does not work
const invoice = {
due_date : new Date("2019-06-13 00:00:00") // EXAMPLE date
}
let date = invoice.due_date.toISOString();
console.log(date)
console.log(date.split(/[T| ]/)[0]); // take space or "T" as delimiter
You can convert the date string to a Date Object:
let dataObj = new Date(date)
and then format it as given in this link

How to format a date in JS

I have created a simple javascript to add 5 days to the current date. I am now having issues getting it to display the format day, date month i.e. Tue 7th Nov. Please can someone help
var newDt = new Date();
newDt.setDate(newDt.getDate() + 5);
document.writeln("" + newDt);
newDt.toDateString()
will return "Tue Nov 12 2017"
Alternatively, you can use a variety of date methods to build a date string that might be more amenable to your needs.
See date methods here:
https://www.w3schools.com/js/js_date_methods.asp
Try out this. If you want it in the format of Weekday Month Day Year remove the .slice(0, -5); on date.
There is plenty of documentation online. You have to look.
Read more about toDateString() here.
Read more about .slice() here.
var newDt = new Date();
newDt.setDate(newDt.getDate() + 5);
var date = newDt.toDateString();
document.writeln("" + date.slice(0, -5));
To make it in the format you want, Weekday Day Month use this example.
var date = new Date();
var locale = "en-us";
var weekdayNumber = date.toLocaleString(locale, { weekday: "short"});
var calenderDay = date.getDate();
var month = date.toLocaleString(locale, { month: "short" });
document.writeln(weekdayNumber + " " + calenderDay + "th " + month);
Be careful with dates like the 1st and 2nd or anything other than th

Javascript date backward

I'm trying to compute the date of the day before using:
var da = new Date('2016-11-25');
nda = new Date(da-86400000);
It seems to work well when printed out using:
document.write(nda);
The output is:
Thu Nov 24 2016 00:00:00 GMT+0000 (WET)
which is correct, but when I do:
document.write(nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay());
I get a wrong output:
2016-10-4
Any suggestion?
You need to do nda.getMonth() + 1.
Months start from 0 so in order to get the right number of the month you must add 1.
Also you need to use getDate() instead of getDay(). getDay will give you the day of the week, while getDate will give you the day of the month.
The end result would be:
nda.getFullYear() + "-" + (nda.getMonth() + 1) + "-" + nda.getDate()
var da = new Date('2016-11-25');
nda = new Date(da-86400000);
document.write((nda.getFullYear())+
"-"+(nda.getMonth()+1)+
"-"+(nda.getDate()));
Date.getMonth() returns the index of the month, which is 0-indexed (So 0 is January, and 11 is December). To correct for this, you add 1.
Date.getDay() returns the day of the week, which is also 0-indexed starting from Sunday (So 4 is Thursday).
Here, you would use Date.getDate() to get the day in the current month (Which is not 0-indexed).
var da = new Date('2016-11-25'),
nda = new Date(da-86400000);
document.write(nda.getFullYear() + "-" +
(nda.getMonth() + 1) + "-" +
nda.getDate());
There is a fundamental rule wiht parsing dates: do not use the Date constructor or Date.parse (they are equivalent for parsing) to parse date strings. Use a library with a parser or parse it yourself with a simple function.
When using:
var da = new Date('2016-11-25');
the date will be treated as UTC, so if you are in a timezone that is west of Greenwich the local date will be the day before. Note the differences in the following:
console.log('Built-in parse: ' + new Date('2016-11-25').toLocaleString());
console.log('No parse : ' + new Date(2016, 10, 25).toLocaleString());
When you do:
nda.getFullYear()+"-"+nda.getMonth()+"-"+nda.getDay();
as others have said, you should use nda.getMonth() + 1, and you want getDate rather than getDay. However, since you are parsing the date as UTC then getting local values, the previous issue with UTC may mean that the date is one day previous.
To construct a date in the local time zone and avoid parsing errors, set the values directly.
To get the day before any date, simply subtract one day. Don't subtract 24 hours or you'll then get errors over daylight saving boundaries (since those days aren't exactly 24 hours long). e.g.:
/* Format a date as yyyy-mm-dd
** #param {Date} date
** #returns {string}
*/
function formatDate(date) {
return date.getFullYear() + '-' +
('0' + (date.getMonth() + 1)).slice(-2) + '-' +
('0' + date.getDate()).slice(-2);
}
var nda = new Date(2016, 10, 25);
console.log('Created date: ' + formatDate(nda));
nda.setDate(nda.getDate() - 1);
console.log('Previous day: ' + formatDate(nda));

Add one day to date in javascript

I am sure that a lot of people asked this question but when I checked the answers it seems to me that they are wrong that what I found
var startDate = new Date(Date.parse(startdate));
//The start date is right lets say it is 'Mon Jun 30 2014 00:00:00'
var endDate = new Date(startDate.getDate() + 1);
// the enddate in the console will be 'Wed Dec 31 1969 18:00:00' and that's wrong it should be 1 july
I know that .getDate() return from 1-31 but Does the browser or the javascript increase only the day without updating the month and the year ?
and in this case Should I write an algorithm to handle this ? or there is another way ?
Note that Date.getDate only returns the day of the month. You can add a day by calling Date.setDate and appending 1.
// Create new Date instance
var date = new Date()
// Add a day
date.setDate(date.getDate() + 1)
JavaScript will automatically update the month and year for you.
EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.
The Date constructor that takes a single number is expecting the number of milliseconds since December 31st, 1969.
Date.getDate() returns the day index for the current date object. In your example, the day is 30. The final expression is 31, therefore it's returning 31 milliseconds after December 31st, 1969.
A simple solution using your existing approach is to use Date.getTime() instead. Then, add a days worth of milliseconds instead of 1.
For example,
var dateString = 'Mon Jun 30 2014 00:00:00';
var startDate = new Date(dateString);
// seconds * minutes * hours * milliseconds = 1 day
var day = 60 * 60 * 24 * 1000;
var endDate = new Date(startDate.getTime() + day);
JSFiddle
Please note that this solution doesn't handle edge cases related to daylight savings, leap years, etc. It is always a more cost effective approach to instead, use a mature open source library like moment.js to handle everything.
There is issue of 31st and 28th Feb with getDate() I use this function getTime and 24*60*60*1000 = 86400000
Use this function:
function incrementDate(dateInput,increment) {
var dateFormatTotime = new Date(dateInput);
var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));
return increasedDate;
}
Example as below:
var dateWith31 = new Date("2017-08-31");
var dateWith29 = new Date("2016-02-29");
var amountToIncreaseWith = 1; //Edit this number to required input
console.log(incrementDate(dateWith31,amountToIncreaseWith));
console.log(incrementDate(dateWith29,amountToIncreaseWith));
function incrementDate(dateInput,increment) {
var dateFormatTotime = new Date(dateInput);
var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));
return increasedDate;
}
use this i think it is useful for you
var endDate=startDate.setDate(startDate.getDate() + 1);
I think what you are looking for is:
startDate.setDate(startDate.getDate() + 1);
Also, you can have a look at Moment.js
A javascript date library for parsing, validating, manipulating, and formatting dates.
var datatoday = new Date();
var datatodays = datatoday.setDate(new Date(datatoday).getDate() + 1);
todate = new Date(datatodays);
console.log(todate);
This will help you...
add one day in javascript in one line
NB: if you want to add a specific number of days ... just replace 1 with the number of days you want
new Date(new Date().setDate(new Date().getDate() + 1))
console.log(new Date(new Date().setDate(new Date().getDate() + 1)))
i know it's been long time since this is posted but here's my answer
function addDays(date, n)
{
const oneDayInMs = 86400 * 1000;
return new Date(Date.parse(date) + (n * oneDayInMs));
}
addDays(new Date(), 1);
Just for the sake of adding functions to the Date prototype:
In a mutable fashion / style:
Date.prototype.addDays = function(n) {
this.setDate(this.getDate() + n);
};
// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
this.addDays(1);
};
Date.prototype.addMonths = function(n) {
this.setMonth(this.getMonth() + n);
};
Date.prototype.addYears = function(n) {
this.setFullYear(this.getFullYear() + n);
}
// etc...
var currentDate = new Date();
currentDate.nextDay();
If you don't mind using a library, DateJS (https://github.com/abritinthebay/datejs/) would make this fairly easy. You would probably be better off with one of the answers using vanilla JavaScript however, unless you're going to take advantage of some other DateJS features like parsing of unusually-formatted dates.
If you're using DateJS a line like this should do the trick:
Date.parse(startdate).add(1).days();
You could also use MomentJS which has similar features (http://momentjs.com/), however I'm not as familiar with it.
The below will add a single day to a current time. I believe this will handle daylight saving times, etc.
function increment_date (date) {
let old_date = new Date (date);
date.setDate (old_date.getDate() + 1);
while (date.getDate() == old_date.getDate()) {
date.setHours (date.getHours() + 1);
}
date.setHours (0);
}

Convert input type text into date format

I have one input type text:
<input type="text" id="policyholder-dob" name="policyholder-dob" />
I want to type number in this field in mm/dd/yyyy format:
like 01/01/2014
This is my js code but its not working, what mistake have I made?
function dateFormatter(date) {
var formattedDate = date.getDate()
+ '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
return formattedDate;
}
var nextduedate = $("#policyholder-dob").val();
var dateFormatDate = nextduedate.slice(0, 2);
var dateFormatMonth = nextduedate.slice(2, 4);
var dateFormatYear = nextduedate.slice(4, 8);
var totalFormat = dateFormatMonth + '/' + dateFormatDate + '/' + dateFormatYear;
var againNewDate = new Date(totalFormat);
againNewDate.setDate(againNewDate.getDate() + 1);
var todaydate = dateFormatter(againNewDate);
$("#policyholder-dob").prop("value", todaydate);
Any help will be really appreciated.
Thankfully, your input is consistently in this format:
mm/dd/yyyy
So you can convert it to a Date object through a custom function, such as:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2],
temp = [];
temp.push(y,m,d);
return (new Date(temp.join("-"))).toUTCString();
}
Or:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2];
return (new Date(y + "-" + m + "-" + d)).toUTCString();
}
Etc..
Calling it is easy:
stringToDate("12/27/1963");
And it will return the correct timestamp in GMT (so that your local timezone won't affect the date (EST -5, causing it to be 26th)):
Fri, 27 Dec 1963 00:00:00 GMT //Late december
Example
There are various ways to accomplish this, this is one of them.
I'd suggest moment.js for date manipulation. You're going to run into a world of hurt if you're trying to add 1 to month. What happens when the month is December and you end up with 13 as your month. Let a library handle all of that headache for you. And you can create your moment date with the string that you pull from the val. You substrings or parsing.
var d = moment('01/31/2014'); // creates a date of Jan 31st, 2014
var duration = moment.duration({'days' : 1}); // creates a duration object for 1 day
d.add(duration); // add duration to date
alert(d.format('MM/DD/YYYY')); // alerts 02/01/2014
Here's a fiddle showing it off.

Categories

Resources