How to determine one year from now in Javascript - javascript

I'm trying to get one year from now's date, and it's not working.
JS:
var now = new Date();
var oneYr = new Date();
oneYr.setYear(now.getYear() + 1);
$("#yearFromNow").append(oneYr.toString());
var oneMonth = new Date();
oneMonth.setMonth(now.getMonth() + 1);
$("#monthFromNow").append(oneMonth.toString());
Output:
one mo. = Thu Dec 22 112 15:16:01 GMT-0500 (Eastern Standard Time)
one yr. = Sun Jan 22 2012 15:16:01 GMT-0500 (Eastern Standard Time)
The year has Dec 22 112 - ?? The month is correctly displaying Jan 22 2012.
If you want to tinker with it, http://jsbin.com/alezaj/edit#javascript,html,live. This is in Chrome and Firefox.
Thanks!

This will create a Date exactly one year in the future with just one line. First we get the fullYear from a new Date, increment it, set that as the year of a new Date. You might think we'd be done there, but if we stopped it would return a timestamp, not a Date object so we wrap the whole thing in a Date constructor.
new Date(new Date().setFullYear(new Date().getFullYear() + 1))

You should use getFullYear() instead of getYear(). getYear() returns the actual year minus 1900 (and so is fairly useless).
Thus a date marking exactly one year from the present moment would be:
var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
Note that the date will be adjusted if you do that on February 29.
Similarly, you can get a date that's a month from now via getMonth() and setMonth(). You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate() and setDate().

As setYear() is deprecated, correct variant is:
// plus 1 year
new Date().setFullYear(new Date().getFullYear() + 1)
// plus 1 month
new Date().setMonth(new Date().getMonth() + 1)
// plus 1 day
new Date().setDate(new Date().getDate() + 1)
All examples return Unix timestamp, if you want to get Date object - just wrap it with another new Date(...)

Use this:
var startDate = new Date();
startDate.setFullYear(startDate.getFullYear() - 1);

Using some of the answers on this page and here,
I came up with my own answer as none of these answers fully solved it for me.
Here is crux of it
var startDate = "27 Apr 2017";
var numOfYears = 1;
var expireDate = new Date(startDate);
expireDate.setFullYear(expireDate.getFullYear() + numOfYears);
expireDate.setDate(expireDate.getDate() -1);
And here a a JSFiddle that has a working example: https://jsfiddle.net/wavesailor/g9a6qqq5/

Use setFullyear as others have posted but be aware this returns a timestamp value not a date object. It is also a good candidate imho to add functionality via the prototype. This leads us to the following pattern:
Date.prototype.addYears = function(n) {
var now = new Date();
return new Date(now.setFullYear(now.getFullYear() + n));
};
console.log('Year from now is', new Date().addYears(1));

In very simple way. use this code.
// define function
function nextYearDate(date1) {
var date2 = new Date(date1);
var date3 = date2.setDate(date2.getDate() - 1);
var date = new Date(date3);
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear()+1;
var newdate = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
$("#next_date").val(newdate);
}
// call function.
<input type="date" name="current_date" id="current_date" value="" onblur="nextYearDate(this.value);" />
<input type="date" name="next_date" id="next_date" value="" onblur="nextYearDate(this.value);" />

Related

Change day in new Date() js without rollover month, year or time

Hello everyone. Can you help me with this kind of question?
I want to encrease days in date string, so code is kind like this.
var date = new Date()
date.setDate(date.getDate() + 1)
The problem is that i want to change only days without month, years or time (h m s). So, for example if i have date 31 december 2021 and i encrease day by one i want to get 01 december 2021 and not 01 january 2022. Is it possible in JS?
You'll just have to manually check and adjust if needed. Here's an example function:
var date = new Date('12/31/2021');
incremenetLoopingDate(date);
console.log(date);
function incremenetLoopingDate(date){
var mo = date.getMonth();
date.setDate(date.getDate() + 1);
if(date.getMonth() !== mo){
date.setMonth(mo);
}
return date;
}
Similar to the other answer, but simpler. Just check if the incremented date is 1 and if so, set to the previous month. Note that this modifies the passed date.
function incrementMonthLoop(date = new Date()) {
date.setDate(date.getDate() + 1);
if (date.getDate() == 1) date.setMonth(date.getMonth() - 1);
return date;
}
console.log(
incrementMonthLoop(new Date(2021, 11, 31)).toDateString()
);

Adding days to a Date object in JavaScript is not working properly

I have read several questions on stack overflow and all over the internet but somehow I am unable to get it right. I get a date from another function and the value is as below.
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate); // this prints Wed Apr 28 2021 00:00:00 GMT+1000 (Australian Eastern Standard Time)
// want to add 45 days to my date
var offset = 45;
var xDate = new Date();
xDate.setDate(currentDate.getDate() + offset);
console.log(xDate);
The output I get is:
Mon Jul 12 2021 19:00:57 GMT+1000 (Australian Eastern Standard Time)
where as this should be some date in June.
Please can someone help me understand what I am doing wrong?
The problem is that when you are initializing a new date object using new Date(), the date object is initialized with the current date. When you increment the days using currentDate.getDate() + offset the day of the month is first set to that of currentDate and incremented by offset but the month from which it is incremented is the current month. Try this one.
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate); // this prints Wed Apr 28 2021 00:00:00 GMT+1000 (Australian Eastern Standard Time)
// want to add 45 days to my date
var offset = 45;
var xDate = new Date("2021-04-27T15:30:27.588+0000");
xDate.setDate(currentDate.getDate() + offset);
console.log(xDate);
1 day is equal to 86,400,000 milliseconds. You can multiply that value by 45 and add it to your date:
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate);
// Add 45 days
var offset = 45;
var xDate = new Date(currentDate.getTime() + offset * 86400000);
console.log(xDate);
My suggestion:
const addDays = (date, days) => {
var ndt = new Date(date);
ndt.setDate(date.getDate() + days);
return ndt;
};
var date = new Date("2021-04-27T15:30:27.588+0000");
console.log(date);
console.log(addDays(date, 45));
I agree Wais Kamal's answer is right. The below code is more succinct since you avoid time calculations
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
var offset = 45;
var xDate = currentDate.setDate(currentDate.getDate() + offset);
console.log(xDate);
You can make use of the moment here. Link to official docs. Don't forget to install moment package like so (assuming you are using npm)
npm i moment
const myDate = "2021-04-27T15:30:27.588+0000";
const updatedDate = moment
.utc(myDate)
.add(45, 'days')
.format('YYYY-MM-DD');
console.log('updatedDate', updatedDate); // "2021-06-11"

Why does adding a month to a Date object return a strange number?

The following returns 11 which is correct.
var month = d.getMonth();
alert(month);
When I try adding a month to it returns something very different
var month = d.setMonth(d.getMonth() + 1);
alert(month);
It returns: 1513230546878
Return values of methods that you are using in your code are as follows
d.getMonth() - A Number, from 0 to 11, representing the month (Link)
d.setMonth() - A Number, representing the number of milliseconds between the date object and midnight January 1 1970 (Link)
Please note, d.setMonth() will modify your Date object in place. So, if you want your code to work as expected, you can write as follows
var d = new Date()
var month = d.getMonth();
alert(month);
d.setMonth(d.getMonth() + 1);
alert(d.getMonth());
d.setMonth() method returns the updated timestamp value (See docs). That's why you got a long number.
If you want to get the month you will use as per below
var d = new Date("2017-10-03");
d.setMonth(d.getMonth() + 1);
var month = d.getMonth(); // get new month
alert(month);
hope it helps
In java script, if you write this:
var month = d.setMonth(d.getMonth() + 1);
You get a timestamp. Meaning, an integer number representing the month you chose.
This is because, setDate accepts a dayValue parameter:
Date.setDate(dayValue)
Meaning that:
var dt = new Date("Aug 28, 2008 23:30:00");
dt.setDate(24);
console.log(dt);
will result in:
Sun Aug 24 2008 23:30:00 //+ your standard gmt time
For further inquire, see this Link
//set date to now:
var d = new Date();
console.log(d);
//just checking
var month = d.getMonth();
console.log(month);
//add a month
d.setMonth(d.getMonth() + 1);
//now the month is one ahead:
console.log(d.getMonth());
console.log(d);

How to convert timestamp to readable date/time?

I have an API result giving out timestamp like this 1447804800000. How do I convert this to a readable format using Javascript/jQuery?
You can convert this to a readable date using new Date() method
if you have a specific date stamp, you can get the corresponding date time format by the following method
var date = new Date(timeStamp);
in your case
var date = new Date(1447804800000);
this will return
Wed Nov 18 2015 05:30:00 GMT+0530 (India Standard Time)
Call This function and pass your date :
JS :
function getDateFormat(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
var date = new Date();
date.toLocaleDateString();
return [day, month, year].join('-');
}
;
In my case, the REST API returned timestamp with decimal. Below code snippet example worked for me.
var ts= 1551246342.000100; // say this is the format for decimal timestamp.
var dt = new Date(ts * 1000);
alert(dt.toLocaleString()); // 2/27/2019, 12:45:42 AM this for displayed

Converting milliseconds to a date (jQuery/JavaScript)

I'm a bit of a rambler, but I'll try to keep this clear -
I'm bored, so I'm working on a "shoutbox", and I'm a little confused over one thing. I want to get the time that a message is entered, and I want to make sure I'm getting the server time, or at least make sure I'm not getting the local time of the user. I know it doesn't matter, since this thing won't be used by anyone besides me, but I want to be thorough. I've looked around and tested a few things, and I think the only way to do this is to get the milliseconds since January 1, 1970 00:00:00 UTC, since that'd be the same for everyone.
I'm doing that like so:
var time = new Date();
var time = time.getTime();
That returns a number like 1294862756114.
Is there a way to convert 1294862756114 to a more readable date, like DD/MM/YYYY HH:MM:SS?
So, basically, I'm looking for JavaScript's equivalent of PHP's date(); function.
var time = new Date().getTime(); // get your number
var date = new Date(time); // create Date object
console.log(date.toString()); // result: Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
If you want custom formatting for your date I offer a simple function for it:
var now = new Date;
console.log( now.customFormat( "#DD#/#MM#/#YYYY# #hh#:#mm#:#ss#" ) );
Here are the tokens supported:
token: description: example:
#YYYY# 4-digit year 1999
#YY# 2-digit year 99
#MMMM# full month name February
#MMM# 3-letter month name Feb
#MM# 2-digit month number 02
#M# month number 2
#DDDD# full weekday name Wednesday
#DDD# 3-letter weekday name Wed
#DD# 2-digit day number 09
#D# day number 9
#th# day ordinal suffix nd
#hhhh# 2-digit 24-based hour 17
#hhh# military/24-based hour 17
#hh# 2-digit hour 05
#h# hour 5
#mm# 2-digit minute 07
#m# minute 7
#ss# 2-digit second 09
#s# second 9
#ampm# "am" or "pm" pm
#AMPM# "AM" or "PM" PM
And here's the code:
//*** This code is copyright 2002-2016 by Gavin Kistner, !#phrogz.net
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
Date.prototype.customFormat = function(formatString){
var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhhh,hhh,hh,h,mm,m,ss,s,ampm,AMPM,dMod,th;
YY = ((YYYY=this.getFullYear())+"").slice(-2);
MM = (M=this.getMonth()+1)<10?('0'+M):M;
MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substring(0,3);
DD = (D=this.getDate())<10?('0'+D):D;
DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substring(0,3);
th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
h=(hhh=this.getHours());
if (h==0) h=24;
if (h>12) h-=12;
hh = h<10?('0'+h):h;
hhhh = hhh<10?('0'+hhh):hhh;
AMPM=(ampm=hhh<12?'am':'pm').toUpperCase();
mm=(m=this.getMinutes())<10?('0'+m):m;
ss=(s=this.getSeconds())<10?('0'+s):s;
return formatString.replace("#hhhh#",hhhh).replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm).replace("#AMPM#",AMPM);
};
You can simply us the Datejs library in order to convert the date to your desired format.
I've run couples of test and it works.
Below is a snippet illustrating how you can achieve that:
var d = new Date(1469433907836);
d.toLocaleString(); // expected output: "7/25/2016, 1:35:07 PM"
d.toLocaleDateString(); // expected output: "7/25/2016"
d.toDateString(); // expected output: "Mon Jul 25 2016"
d.toTimeString(); // expected output: "13:35:07 GMT+0530 (India Standard Time)"
d.toLocaleTimeString(); // expected output: "1:35:07 PM"
Below is a snippet to enable you format the date to a desirable output:
var time = new Date();
var time = time.getTime();
var theyear = time.getFullYear();
var themonth = time.getMonth() + 1;
var thetoday = time.getDate();
document.write("The date is: ");
document.write(theyear + "/" + themonth + "/" + thetoday);
Try using this code:
var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
year: 'numeric', month: 'numeric', day: 'numeric',
};
var result = date.toLocaleDateString('en', options); // 10/29/2013
See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Try using this code:
var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
var newDate = new Date(milisegundos).toLocaleDateString("en-UE");
Enjoy it!
so you need to pass that var time after getTime() into another new Date()
here is my example:
var time = new Date()
var time = time.getTime()
var newTime = new Date(time)
console.log(newTime)
//Wed Oct 20 2021 15:21:12 GMT+0530 (India Standard Time)
here output is my datetime standard format for you it will be in country format
if you want it in another format then you can apply another date function on var newTime
like
var newTime = new Date(time).toDateString()
console.log(newTime)
//Wed Oct 20 2021
Try this one :
var time = new Date().toJSON();
One line code.
var date = new Date(new Date().getTime());
or
var date = new Date(1584120305684);
/Date(1383066000000)/
function convertDate(data) {
var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
var ConvDate= new Date(getdate);
return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}
Assume the date as milliseconds date is 1526813885836, so you can access the date as string with this sample code:
console.log(new Date(1526813885836).toString());
For clearness see below code:
const theTime = new Date(1526813885836);
console.log(theTime.toString());
use datejs
new Date().toString('yyyy-MM-d-h-mm-ss');

Categories