Add one day to date in javascript - 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);
}

Related

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.

Add time to datetime and return the date and time javascript [duplicate]

I'd like to get a Date object which is 30 minutes later than another Date object. How do I do it with JavaScript?
Using a Library
If you are doing a lot of date work, you may want to look into JavaScript date libraries like Datejs or Moment.js. For example, with Moment.js, this is simply:
var newDateObj = moment(oldDateObj).add(30, 'm').toDate();
Vanilla Javascript
This is like chaos's answer, but in one line:
var newDateObj = new Date(oldDateObj.getTime() + diff*60000);
Where diff is the difference in minutes you want from oldDateObj's time. It can even be negative.
Or as a reusable function, if you need to do this in multiple places:
function addMinutes(date, minutes) {
return new Date(date.getTime() + minutes*60000);
}
And just in case this is not obvious, the reason we multiply minutes by 60000 is to convert minutes to milliseconds.
Be Careful with Vanilla Javascript. Dates Are Hard!
You may think you can add 24 hours to a date to get tomorrow's date, right? Wrong!
addMinutes(myDate, 60*24); //DO NOT DO THIS
It turns out, if the user observes daylight saving time, a day is not necessarily 24 hours long. There is one day a year that is only 23 hours long, and one day a year that is 25 hours long. For example, in most of the United States and Canada, 24 hours after midnight, Nov 2, 2014, is still Nov 2:
const NOV = 10; //because JS months are off by one...
addMinutes(new Date(2014, NOV, 2), 60*24); //In USA, prints 11pm on Nov 2, not 12am Nov 3!
This is why using one of the afore-mentioned libraries is a safer bet if you have to do a lot of work with this.
Below is a more generic version of this function that I wrote. I'd still recommend using a library, but that may be overkill/impossible for your project. The syntax is modeled after MySQL DATE_ADD function.
/**
* Adds time to a date. Modelled after MySQL DATE_ADD function.
* Example: dateAdd(new Date(), 'minute', 30) //returns 30 minutes from now.
* https://stackoverflow.com/a/1214753/18511
*
* #param date Date to start with
* #param interval One of: year, quarter, month, week, day, hour, minute, second
* #param units Number of units of the given interval to add.
*/
function dateAdd(date, interval, units) {
if(!(date instanceof Date))
return undefined;
var ret = new Date(date); //don't change original date
var checkRollover = function() { if(ret.getDate() != date.getDate()) ret.setDate(0);};
switch(String(interval).toLowerCase()) {
case 'year' : ret.setFullYear(ret.getFullYear() + units); checkRollover(); break;
case 'quarter': ret.setMonth(ret.getMonth() + 3*units); checkRollover(); break;
case 'month' : ret.setMonth(ret.getMonth() + units); checkRollover(); break;
case 'week' : ret.setDate(ret.getDate() + 7*units); break;
case 'day' : ret.setDate(ret.getDate() + units); break;
case 'hour' : ret.setTime(ret.getTime() + units*3600000); break;
case 'minute' : ret.setTime(ret.getTime() + units*60000); break;
case 'second' : ret.setTime(ret.getTime() + units*1000); break;
default : ret = undefined; break;
}
return ret;
}
Working jsFiddle demo.
var d1 = new Date (),
d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 30 );
alert ( d2 );
var oldDateObj = new Date();
var newDateObj = new Date();
newDateObj.setTime(oldDateObj.getTime() + (30 * 60 * 1000));
console.log(newDateObj);
var now = new Date();
now.setMinutes(now.getMinutes() + 30); // timestamp
now = new Date(now); // Date object
console.log(now);
Maybe something like this?
var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+30);
console.log(v)
I always create 7 functions, to work with date in JS:
addSeconds, addMinutes, addHours, addDays, addWeeks, addMonths, addYears.
You can see an example here: http://jsfiddle.net/tiagoajacobi/YHA8x/
How to use:
var now = new Date();
console.log(now.addMinutes(30));
console.log(now.addWeeks(3));
These are the functions:
Date.prototype.addSeconds = function(seconds) {
this.setSeconds(this.getSeconds() + seconds);
return this;
};
Date.prototype.addMinutes = function(minutes) {
this.setMinutes(this.getMinutes() + minutes);
return this;
};
Date.prototype.addHours = function(hours) {
this.setHours(this.getHours() + hours);
return this;
};
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
Date.prototype.addWeeks = function(weeks) {
this.addDays(weeks*7);
return this;
};
Date.prototype.addMonths = function (months) {
var dt = this.getDate();
this.setMonth(this.getMonth() + months);
var currDt = this.getDate();
if (dt !== currDt) {
this.addDays(-currDt);
}
return this;
};
Date.prototype.addYears = function(years) {
var dt = this.getDate();
this.setFullYear(this.getFullYear() + years);
var currDt = this.getDate();
if (dt !== currDt) {
this.addDays(-currDt);
}
return this;
};
One line code
var afterSomeMinutes = new Date(new Date().getTime() + minutes * 60000);
where minutes is a number
Stop using Moment.js
As recommended by other great answers, in most cases it's best to use a library when dealing dates. However, it's important to know that as of September 2020 Moment.js is considered legacy and should no longer be used in new projects.
Quoting Moment's statement in their official docs:
We would like to discourage Moment from being used in new projects going forward. [...] We now generally consider Moment to be a legacy project in maintenance mode. It is not dead, but it is indeed done.
Modern libraries
Below are alternatives recommended by Moment.
Luxon
Luxon can be thought of as the evolution of Moment. It is authored by Isaac Cambron, a long-time contributor to Moment. Please read Why does Luxon exist? and the For Moment users pages in the Luxon documentation.
Locales: Intl provided
Time Zones: Intl provided
import {DateTime} from 'luxon'
function addMinutes(date, minutes) {
return DateTime.fromJSDate(date).plus({minutes}).toJSDate()
}
Day.js
Day.js is designed to be a minimalist replacement for Moment.js, using a similar API. It is not a drop-in replacement, but if you are used to using Moment's API and want to get moving quickly, consider using Day.js.
Locales: Custom data files that can be individually imported
Time Zones: Intl provided, via a plugin
import dayjs from 'dayjs'
function addMinutes(date, minutes) {
return dayjs(date).add(minutes, 'minutes').toDate()
}
date-fns
Date-fns offers a series of functions for manipulating JavaScript Date objects. For more details, scroll to "Why date-fns?" on the date-fns home page.
Locales: Custom data files that can be individually imported
Time Zones: Intl provided, via a separate companion library
import {addMinutes} from 'date-fns'
function addMinutesDemo(date, minutes) {
return addMinutes(date, minutes)
}
js-Joda
js-Joda is a JavaScript port of Java's Three-Ten Backport, which is the base for JSR-310 implementation of the Java SE 8 java.time package. If you are familiar with java.time, Joda-Time, or Noda Time, you will find js-Joda comparable.
Locales: Custom data files via add-on module
Time Zones: Custom data files via add-on module
import {LocalDateTime, nativeJs, convert} from '#js-joda/core'
function addMinutes(date, minutes) {
return convert(
LocalDateTime.from(
nativeJs(date)
).plusMinutes(minutes)
).toDate()
}
One-liner no utilities:
new Date(+new Date() + 60000*15) // +15 minutes
The easiest way to solve is the to recognize that in javascript dates are just numbers. It starts 0 or 'Wed Dec 31 1969 18:00:00 GMT-0600 (CST). Every 1 represents a millisecond. You can add or subtract milliseconds by getting the value and instantiating a new date using that value. You can manage it pretty easy with that mind.
const minutesToAdjust = 10;
const millisecondsPerMinute = 60000;
const originalDate = new Date('11/20/2017 10:00 AM');
const modifiedDate1 = new Date(originalDate.valueOf() - (minutesToAdjust * millisecondsPerMinute));
const modifiedDate2 = new Date(originalDate.valueOf() + (minutesToAdjust * millisecondsPerMinute));
console.log(originalDate); // Mon Nov 20 2017 10:00:00 GMT-0600 (CST)
console.log(modifiedDate1); // Mon Nov 20 2017 09:50:00 GMT-0600 (CST)
console.log(modifiedDate2); // Mon Nov 20 2017 10:10:00 GMT-0600 (CST)
This is what I do which seems to work quite well:
Date.prototype.addMinutes = function(minutes) {
var copiedDate = new Date(this.getTime());
return new Date(copiedDate.getTime() + minutes * 60000);
}
Then you can just call this like this:
var now = new Date();
console.log(now.addMinutes(50));
You should get the value of the current date to get the date with (ms) and add (30 * 60 *1000) to it. Now you have (current date + 30 min) with ms
console.log('with ms', Date.now() + (30 * 60 * 1000))
console.log('new Date', new Date(Date.now() + (30 * 60 * 1000)))
it is simple as it is;
let initial_date = new Date;
let added30Min = new Date(initial_date.getTime() + (30*60*1000));
Here is the ES6 version:
let getTimeAfter30Mins = () => {
let timeAfter30Mins = new Date();
timeAfter30Mins = new Date(timeAfter30Mins.setMinutes(timeAfter30Mins.getMinutes() + 30));
};
Call it like:
getTimeAfter30Mins();
Here is my one-liner:
console.log('time: ', new Date(new Date().valueOf() + 60000))
I feel many of the answers here are lacking a creative component, very much needed for time travel computations. I present my solution for a temporal translation of 30 minutes.
(jsfiddle here)
function fluxCapacitor(n) {
var delta,sigma=0,beta="ge";
(function(K,z){
(function(a,b,c){
beta=beta+"tT";
switch(b.shift()) {
case'3':return z('0',a,c,b.shift(),1);
case'0':return z('3',a,c,b.pop());
case'5':return z('2',a,c,b[0],1);
case'1':return z('4',a,c,b.shift());
case'2':return z('5',a,c,b.pop());
case'4':return z('1',a,c,b.pop(),1);
}
})(K.pop(),K.pop().split(''),K.pop());
})(n.toString().split(':'),function(b,a,c,b1,gamma){
delta=[c,b+b1,a];sigma+=gamma?3600000:0;
beta=beta+"im";
});
beta=beta+"e";
return new Date (sigma+(new Date( delta.join(':')))[beta]());
}
You could do this:
let thirtyMinutes = 30 * 60 * 1000; // convert 30 minutes to milliseconds
let date1 = new Date();
let date2 = new Date(date1.getTime() + thirtyMinutes);
console.log(date1);
console.log(date2);
Here is the IsoString version:
console.log(new Date(new Date().setMinutes(new Date().getMinutes() - (30))).toISOString());
var add_minutes = function (dt, minutes) {
return new Date(dt.getTime() + minutes*60000);
}
console.log(add_minutes(new Date(2014,10,2), 30).toString());
One way to 'add' 30 minutes is to create a second date object (mostly for demonstration) and set the minutes to minutes + 30. This will account for adjusting the hour as well if the first time is less than 30 minutes from the next hour. (i.e., 4:45 to 5:15)
const first = new Date();
console.log("first date :", first.toString());
const second = new Date(first);
const newMinutes = second.getMinutes() + 30;
console.log("new minutes:", newMinutes);
second.setMinutes(newMinutes);
console.log("second date:", second.toString());
I know that the topic is way too old. But I am pretty sure that there are some developpers who still need this, so I made this simple script for you.
I hope you enjoy it!
Hello back, It's 2020 and I've added some modification hope it will help a lot better now!
Hello again, It is 2022 and I came back again to fix some issues and give a better naming for the methods & functions.
function addTimeToDate(addedTime, date){
let generatedTime = date.getTime();
if(addedTime.seconds) generatedTime += 1000 * addedTime.seconds; //check for additional seconds
if(addedTime.minutes) generatedTime += 1000* 60 * addedTime.minutes;//check for additional minutes
if(addedTime.hours) generatedTime += 1000 * 60 * 60 * addedTime.hours;//check for additional hours
return new Date(generatedTime);
}
Date.prototype.addTime = function(addedTime){
return addTimeToDate(addedTime, this);
}
let futureDate = new Date().addTime({
hours: 16, //Adding one hour
minutes: 45, //Adding fourty five minutes
seconds: 0 //Adding 0 seconds return to not adding any second so we can remove it.
});
<button onclick="console.log(futureDate)">Travel to the future</button>
Use an existing library known to handle the quirks involved in dealing with time calculations. My current favorite is moment.js.
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script>
var now = moment(); // get "now"
console.log(now.toDate()); // show original date
var thirty = moment(now).add(30,"minutes"); // clone "now" object and add 30 minutes, taking into account weirdness like crossing DST boundries or leap-days, -minutes, -seconds.
console.log(thirty.toDate()); // show new date
</script>
Other solution:
var dateAv = new Date();
var endTime = new Date(dateAv.getFullYear(), dateAv.getMonth(), dateAv.getDate(), dateAv.getHours(), dateAv.getMinutes() + 30);
let d = new Date();
d.setMinutes(d.getMinutes() + 30);
// console.log(d)
For the lazy like myself:
Kip's answer (from above) in coffeescript, using an "enum", and operating on the same object:
Date.UNIT =
YEAR: 0
QUARTER: 1
MONTH: 2
WEEK: 3
DAY: 4
HOUR: 5
MINUTE: 6
SECOND: 7
Date::add = (unit, quantity) ->
switch unit
when Date.UNIT.YEAR then #setFullYear(#getFullYear() + quantity)
when Date.UNIT.QUARTER then #setMonth(#getMonth() + (3 * quantity))
when Date.UNIT.MONTH then #setMonth(#getMonth() + quantity)
when Date.UNIT.WEEK then #setDate(#getDate() + (7 * quantity))
when Date.UNIT.DAY then #setDate(#getDate() + quantity)
when Date.UNIT.HOUR then #setTime(#getTime() + (3600000 * quantity))
when Date.UNIT.MINUTE then #setTime(#getTime() + (60000 * quantity))
when Date.UNIT.SECOND then #setTime(#getTime() + (1000 * quantity))
else throw new Error "Unrecognized unit provided"
# # for chaining
Just another option, which I wrote:
DP_DateExtensions Library
It's overkill if this is all the date processing that you need, but it will do what you want.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.
simply you can use this code with momnet library:
console.log(moment(moment()).add(30,"minutes").format('MM/DD/YYYY hh:mm:ss'));
var myDate= new Date();
var MyNewDate = new Date
(myDate.getFullYear(),myDate.getMonth(),myDate.getDate(),myDate.getMinutes()+10,01,01)
const MINUTE = 60 * 1000;
new Date(Date.parse(yourDate) + numOfMins * MINUTE)

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

How to add weeks to date using 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);

jQuery Format Time

I have a jQuery script that receives a string in milliseconds inside a parameter, like this:
params.tweetDate='77771564221';
What I need to do is to create a jQuery function that will be able to format this milliseconds string in a USA time, like 10.00 AM or 10.00 PM.
Is there a jQuery function that is able to do this?
Please help.
Thanks
There is Date object in pure javascript, no jQuery needed.
http://www.javascriptkit.com/jsref/date.shtml
Example:
var time = new Date(params.tweetDate),
h = time.getHours(), // 0-24 format
m = time.getMinutes();
// next just convert to AM/PM format (check if h > 12)
No, there's no jQuery function for this. You can use
JavaScript's own Date object, using the getHours() and getMinutes() functions, handling the AM/PM thing yourself (e.g., hours >= 12 is PM), padding out the minutes with a leading 0 if minutes is less than 10, etc. Also note that if hours is 0, you want to make it 12 (because when using the AM/PM style, you write midnight as "12:00 AM", not "0:00 AM").
DateJS, an add-on library that does a huge amount of date stuff (although sadly it's not actively maintained)
PrettyDate from John Resig (the creator of jQuery)
To use just about any of those, first you have to turn that "milliseconds" value into a Date object. If it's really a "milliseconds" value, then first you parse the string into a number via parseInt(str, 10) and then use new Date(num) to create the Date object representing that point in time. So:
var dt = new Date (parseInt(params.tweetDate, 10));
However, the value you've quoted, which you said is a milliseconds value, seems a bit odd — normally it's milliseconds since The Epoch (Jan 1, 1970), which is what JavaScript uses, but new Date(parseInt("77771564221", 10)) gives us a date in June 1972, long before Twitter. It's not seconds since The Epoch either (a fairly common Unix convention), because new Date(parseInt("77771564221", 10) * 1000) gives us a date in June 4434. So the first thing to find out is what that value actually represents, milliseconds since when. Then adjust it so it's milliseconds since The Epoch, and feed it into new Date() to get the object.
Here is a function for you:
function timeFormatter(dateTime){
var date = new Date(dateTime);
if (date.getHours()>=12){
var hour = parseInt(date.getHours()) - 12;
var amPm = "PM";
} else {
var hour = date.getHours();
var amPm = "AM";
}
var time = hour + ":" + date.getMinutes() + " " + amPm;
console.log(time);
return time;
}
You may call the function in any approach like:
var time = timeFormatter(parseInt("2345678998765"));
take a look at timeago: this is a jquery plugin used exactly for this purposes.
Using T.J.'s solution this is what I ended up with.
var date = new Date(parseInt("77771564221", 10));
var result = new Array();
result[0] = $.datepicker.formatDate('DD, M, d, yy', date);
result[1] = ' ';
if (date.getHours() > 12) {
result[2] = date.getHours() - 12;
} else if (date.getHours() == 0 ) {
result[2] = "12";
} else {
result[2] = date.getHours();
}
result[3] = ":"
result[4] = date.getMinutes();
if (date.getHours() > 12) {
result[5] = " pm";
} else {
result[5] = " am";
}
console.log(result.join(''));

Categories

Resources