Related
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"
This question already has answers here:
How to add days to Date?
(56 answers)
Closed 2 years ago.
I am trying to pull some historical data, which has a variety of time stamps. I want the use to a user selected date, and then pull all days + some additional days.
Date1 is
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1)
var Enddate = new Date();
Enddate.setDate(startDate + 10);
This doesn't work. I cant seem to figure out how to add the "10 days" to the Date1 variable.
You need the getDate function of the Date object, and you'll need to pass the correct value when instantiating the new Date.
Try this:
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1);
// add it to startDate, using getDate()
startDate.setDate(startDate.getDate() + 10);
// now startDate will be 10 days later:
startDate; // Sun Nov 01 00:00:00 GMT-04:00 2020
// if you want an entirely new Date object, then instantiate a new one:
var Enddate = new Date(startDate);
If you want two different variables, then you can use the approach similar to what you tried, like so:
var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1), second = new Date(Date1); // we're using another temporary variable
// add the days
second.setDate(second.getDate() + 10);
// now use Enddate with this
var Enddate = new Date(second);
Enddate; // Sun Nov 01 00:00:00 GMT-04:00 2020
You can't just add a number to a Date object to get a new date.
You can add to a date by:
getting the current day of the month with getDate()
adding a number of days to that result
setting the new date with setDate()
const Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020";
const addDays = 10;
const startDate = new Date(Date1);
const startDays = startDate.getDate();
const newDate = new Date(startDate);
newDate.setDate(startDays + addDays);
console.log('startDate:', startDate.toISOString());
console.log('newDate:', newDate.toISOString());
Note:
Passing a string into the Date constructor is discouraged, as it produces inconsistent results across browsers.
It is better to pass in the individual date and time values:
const Date1 = new Date(2020, 9, 22, 0, 0, 0);
I have this string for example "November 8, 2016 - December 7, 2016" which I want to extract the two dates in the this format: YYYY-MM-DD.
Now, I managed to get the dates in the format I want in the following way:
HTML:
<span id="selecDate">November 8, 2016 - December 7, 2016</span>
Javascript:
date = $('#selecDate').text().split('-');
begin = new Date(date[1]);
begin = begin.toISOString().split('T')[0];
The problem is that date = ["November 8, 2016 ", " December 7, 2016"]
and begin = "Wed Dec 07 2016 00:00:00 GMT+0200 (IST)"
when in second line but in the last line the value of begin changes to "2016-12-06", one day earlier. Any idea how can I avoid it?
I'm working from (GMT+02:00) time zone
When you execute toISOString() the date you get back is in UTC time so it takes the time back 2 hours (because of your current timezone). Midnight on Dec 06 in IST is 22:00 in UTC time the day before.
If you wish to keep your timestamps in local time, you can use a .toLocaleDateString(), toLocaleString() or even just .toString() on your date object:
begin = new Date('December 7, 2016').toLocaleDateString();
Note that the date format is slightly different:
a.toLocaleDateString()
"12/7/2016"
a.toLocaleString()
"12/7/2016, 12:00:00 AM"
a.toString()
"Wed Dec 07 2016 00:00:00 GMT+0200 (IST)"
As MDN says in, method toISOString():
The timezone is always zero UTC offset.
And when you create your new Date('December 7, 2016'), what you get is:
Wed Dec 07 2016 00:00:00 GMT+0200
So in UTC, the hours are subtracted by 2, giving you the day before.
Solution:
begin = begin.getFullYear() + '-' + (begin.getMonth() + 1) + '-' + begin.getDate();
will result in: "2016-12-07".
date = ["November 8, 2016 ", " December 7, 2016"];
var b = new Date(date[1]);
//use these get methods to avoid all the confusion
var begin = b.getFullYear()+"-"+(b.getMonth()+1)+"-"+b.getDate();
console.log(_begin);
You should not parse strings with the Date constructor, especially when they are a format other than that specified in ECMA-262 as the behaviour is implementation dependent.
If you need Date objects, you should either use a library (e.g. moment.js, fecha.js) and provide the format to parse or write a simple function to parse the format to a date (see below).
However, if you just want a string in a different format, just reformat the string and avoid Dates altogether:
// Reformat a date string in format MMMM d, yyyy to yyyy-mm-dd
function reformatDate(s) {
var b = s.match(/\w+/g) || [];
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
return b.length == 3? b[2] + '-' +
months[b[0].toLowerCase().substr(0,3)] + '-' +
('0' + b[1]).slice(-2) : '';
}
console.log(reformatDate('November 8, 2016'))
The following functions parse a date in MMMM d, yyyy format to a Date object, then format it in yyyy-mm-dd format:
// Parse date string in format MMMM d, yyyy e.g. November 8, 2016
function parseDate(s) {
var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
var b = s.match(/\w+/g) || [];
var m = months.indexOf(b[0].toLowerCase().substr(0,3));
var d = new Date(b[2], m, b[1]);
return d && d.getMonth() == m? d : new Date(NaN);
}
function toISODate(d) {
function z(n){return (n<10?'0':'')+n}
return d.getFullYear() + '-' + z(d.getMonth()+1) + '-' + z(d.getDate());
}
console.log(toISODate(parseDate('November 8, 2016')))
Using a library like moment.js you'd do:
'November 8, 2016 - December 7, 2016'.split(' - ').forEach(function(s) {
var d = moment(s,'MMMM D, YYYY').format('YYYY-MM-DD');
console.log(d);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
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');
I have some javascript which parses an ISO-8601 date. For some reason, it is failing for dates in June. But dates in July and May work fine, which doesn't make sense to me. I'm hoping a fresh set of eyes will help, because I can't see what I'm doing wrong here.
Function definition (with bug)
function parseISO8601(timestamp)
{
var regex = new RegExp("^([\\d]{4})-([\\d]{2})-([\\d]{2})T([\\d]{2}):([\\d]{2}):([\\d]{2})([\\+\\-])([\\d]{2}):([\\d]{2})$");
var matches = regex.exec(timestamp);
if(matches != null)
{
var offset = parseInt(matches[8], 10) * 60 + parseInt(matches[9], 10);
if(matches[7] == "-")
offset = -offset;
var date = new Date();
date.setUTCFullYear(parseInt(matches[1], 10));
date.setUTCMonth(parseInt(matches[2], 10) - 1); //UPDATE - this is wrong
date.setUTCDate(parseInt(matches[3], 10));
date.setUTCHours(parseInt(matches[4], 10));
date.setUTCMinutes(parseInt(matches[5], 10) - offset);
date.setUTCSeconds(parseInt(matches[6], 10));
date.setUTCMilliseconds(0);
return date;
}
return null;
}
Test code
alert(parseISO8601('2009-05-09T12:30:00-00:00').toUTCString());
alert(parseISO8601('2009-06-09T12:30:00-00:00').toUTCString());
alert(parseISO8601('2009-07-09T12:30:00-00:00').toUTCString());
Output
Sat, 09 May 2009 12:30:00 GMT
Thu, 09 Jul 2009 12:30:00 GMT
Thu, 09 Jul 2009 12:30:00 GMT
Update
Thanks for the quick answers, the problem was that the Date object was initially today, which happened to be July 31. When the month was set to June, before I changed the day, it was temporarily June 31, which got rolled forward to July 1.
I've since found the following to be a cleaner implementation, as it sets all the date attributes at once:
function parseISO8601(timestamp)
{
var regex = new RegExp("^([\\d]{4})-([\\d]{2})-([\\d]{2})T([\\d]{2}):([\\d]{2}):([\\d]{2})([\\+\\-])([\\d]{2}):([\\d]{2})$");
var matches = regex.exec(timestamp);
if(matches != null)
{
var offset = parseInt(matches[8], 10) * 60 + parseInt(matches[9], 10);
if(matches[7] == "-")
offset = -offset;
return new Date(
Date.UTC(
parseInt(matches[1], 10),
parseInt(matches[2], 10) - 1,
parseInt(matches[3], 10),
parseInt(matches[4], 10),
parseInt(matches[5], 10),
parseInt(matches[6], 10)
) - offset*60*1000
);
}
return null;
}
The problem is that today is July 31.
When you set:
var date = new Date();
Then date.getUTCDate() is 31. When you set date.setUTCMonth(5) (for June), you are setting date to June 31. Because there is no June 31, the JavaScript Date object turns it into July 1. So immediately after setting calling date.setUTCMonth(5) if you alert(date.getUTCMonth()); it will be 6.
This isn't unique to June. Using your function on the 31st of any month for any other month that does not have 31 days will exhibit the same problem. Using your function on the 29th (non-leap years), 30th or 31st of any month for February would also return the wrong result.
Calling setUTC*() in such a way that any rollovers are overwritten by the correct value should fix this:
var date = new Date();
date.setUTCMilliseconds(0);
date.setUTCSeconds(parseInt(matches[6], 10));
date.setUTCMinutes(parseInt(matches[5], 10) - offset);
date.setUTCHours(parseInt(matches[4], 10));
date.setUTCDate(parseInt(matches[3], 10));
date.setUTCMonth(parseInt(matches[2], 10) - 1);
date.setUTCFullYear(parseInt(matches[1], 10));
The date object starts off with the current date.
It's the 31st today so setting 2009-06-09 gives:
var date = new Date(); // Date is 2009-07-31
date.setUTCFullYear(2009); // Date is 2009-07-31
date.setUTCMonth(6 - 1); // Date is 2009-06-31 = 2009-07-01
date.setUTCDate(9); // Date is 2009-07-09
If you set the date to the 1st before you begin, then you should be safe.
It's because today is July 31. Grant explained the problem. Here's what I believe is a simpler solution. Initialize your date on Jan 1.
var date = new Date(2009,0,1,0,0,0);
It's the order in which you are changing the date.
The date starts out as July 31, so the set of the month fails because there is no 31 in June. (Actually it is rolling over to jul-1.)
After setting the full year, add this:
date.setYUTCDate(1);
It makes it the first of the month wherein every month is valid.
Looks like a bug?
C:\Documents and Settings\me>java org.mozilla.javascript.tools.shell.Main
Rhino 1.7 release 2 2009 03 22
js> date = new Date();
Fri Jul 31 2009 15:18:38 GMT-0400 (EDT)
js> date.setUTCMonth(5); date.toUTCString();
Wed, 01 Jul 2009 19:18:38 GMT
js> date.setUTCMonth(5); date.toUTCString();
Mon, 01 Jun 2009 19:18:38 GMT
EDIT: Nevermind I guess. Question already answered by somebody more knowledgable.