DateTime new Date(params) in javascript is faster by 1 month - javascript

It is very weird but it seems that new Date(params), when passed in the correct format of year, month, day, hours, minutes, seconds, milliseconds, it is ahead by 1 month.
Take a look at the following implementation:
// The format below needs to be changed according to req.param('dateTime')
// dateTime format is as follows: "dd/MM/yyyy HH:mm:ss"
var dateTime = report['dateTime'];
console.log('dateTime: '+dateTime);
var dateTimeSplit = dateTime.split(' ');
var dateSplit = dateTimeSplit[0].split('/');
var timeSplit = dateTimeSplit[1].split(':');
var day = parseInt(dateSplit[0]);
var month = parseInt(dateSplit[1]);
var year = parseInt(dateSplit[2]);
var hour = parseInt(timeSplit[0]);
var minute = parseInt(timeSplit[1]);
var second = parseInt(timeSplit[2]);
var createdAt = new Date(year, month, day, hour, minute, second, 0);
console.log('createdAt: '+createdAt);
And the results from the logs are:
Feb 09 04:13:46 sails-wusrs app/web.1: createdAt: Mon Mar 09 2015 12:02:24 GMT+0000 (UTC)
Feb 09 04:13:46 sails-wusrs app/web.1: dateTime: 09/02/2015 12:02:24
This server is running on heroku and it's weird that the log of createdAt is in front of dateTime. Everything else is alright, except for the month. 02 is Feb right? I'm so confused. Thanks for any help!

Month in javascript datetime starts from 0.
http://javascript.info/tutorial/datetime-functions

Related

Tricky date string to parse in JavaScript

Fri Nov 10 05:45:36 +0000 2017
I've tried both moment and chrono-node. Both are getting stumped by this date format.
Any suggestions to get a valid UTC date?
Thanks
To add to #CertainPerformance's answer, the problem with your code, if you try with MomentJS is that it is not a standard ISO date string. Parsing it directly without specifying format will result in incorrect result and a warning like this:
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release.
To mitigate, always pass the format to MomentJS constructor like this:
const inputStr = "Fri Nov 10 05:45:36 +0000 2017"
const mom = moment(inputStr, 'ddd MMM D HH:mm:ss ZZ YYYY');
console.log(mom.toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
I think this should help you out:
var date = new Date("Fri Nov 10 05:45:36 +0000 2017").toISOString();
date = date.split("T")[0];
console.log(date);
Moment works just fine:
const inputStr = "Fri Nov 10 05:45:36 +0000 2017"
const mom = moment(inputStr, 'ddd MMM D HH:mm:ss ZZ YYYY');
console.log(mom.toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
You can see the difference between 2 items of each array which is returned by the code that I have written to process the date strings of the form you have provided.
Finally you can have a look at the full code example given.
In first case, both are same.
In second case, both are different.
console.log(dateArr1); // [ '2017-11-10', '2017-11-10' ];
console.log(dateArr2); // [ '2018-05-15', '2018-05-14' ];
So it's clear our UTC conversion is working fine.
Please have a look at the below code example and try to understand. It is simple.
Note» All the comments inside function are for inputDateStr: "Fri Nov 10 05:45:36 +0000 2017"
// All the comments inside function are for
// inputDateStr: "Fri Nov 10 05:45:36 +0000 2017"
function getMyUTCDate(inputDateStr)
{
var inputDateString = inputDateStr;
var date = new Date(inputDateString);
var dateArr = []; // To store 2 dates, simple one & full UTC one
console.log(date); // 2017-11-10T05:45:36.000Z
// ............... SIMPLE EXAMPLE ..........................
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes()
var seconds = date.getSeconds();
console.log(year); // 2017
console.log(month); // 10
console.log(day); // 10
console.log(hours); // 11
console.log(minutes); // 15
console.log(seconds); // 36
utcDate = new Date(Date.UTC(year, month, day, hours, minutes, seconds));
utcDateString = utcDate.toUTCString();
console.log(utcDate); // 2017-11-10T11:15:36.000Z
console.log(utcDateString); // Fri, 10 Nov 2017 11:15:36 GMT
var dt1 = utcDate.toISOString().split('T')[0]
dateArr.push(dt1)
console.log(dt1); // 2017-11-10
// .................. FULL UTC EXAMPLE ..........................
var utcYear = date.getUTCFullYear();
var utcMonth = date.getUTCMonth();
var utcDay = date.getUTCDate();
var utcHours = date.getUTCHours();
var utcMinutes = date.getUTCMinutes()
var utcSeconds = date.getUTCSeconds();
console.log(utcYear); // 2017
console.log(utcMonth); // 10
console.log(utcDay); // 10
console.log(utcHours); // 5
console.log(utcMinutes);// 45
console.log(utcSeconds);// 36
var utcDate2 = new Date(Date.UTC(utcYear, utcMonth, utcDay, utcHours, utcMinutes, utcSeconds));
var utcDateString2 = utcDate2.toUTCString();
console.log(utcDate2); // 2017-11-10T05:45:36.000Z
console.log(utcDateString2); // Fri, 10 Nov 2017 05:45:36 GMT
// Get UTC Date
var dt2 = utcDate2.toISOString().split('T')[0]
dateArr.push(dt2)
console.log(dt2); // 2017-11-10
return dateArr;
}
// Inputs
var inputDateString1 = "Fri Nov 10 05:45:36 +0000 2017";
var inputDateString2 = "Mon May 14 23:59:36 +0000 2018";
var dateArr1 = getMyUTCDate(inputDateString1);
var dateArr2 = getMyUTCDate(inputDateString2);
// Print dates
console.log(dateArr1); // [ '2017-11-10', '2017-11-10' ]
console.log(dateArr2); // [ '2018-05-15', '2018-05-14' ]
References
developer.mozilla.org - Date processing functions
Thanks.

Javascript Converting Ints to Time?

For a project app I'm making, a homework keeper, I need to be able to turn a number like 10 into a month like october, then do this with year, month, day, and time. Then I need to save it all in a date. How do I do this? I have been looking everywhere and cannot find how to do it.
It looks like you're looking for the Date() constructor.
var month = 10;
var day = 17;
var year = 2017;
var hour = 8;//Use the 24 hour clock for times in the PM
var minutes = 36;
var date = new Date(year, month-1, day, hour, minutes);//Outputs October 17th, 2017 at 8:36am in your local timezone
You have to subtract 1 from the month because January starts at 0, not 1.
Alternatively, I like to use moment.js for the flexibility depending on use, so you could instantiate it like this:
var date = moment(year + '-' + month + '-' + day + ' ' + hour + ':' + minutes, 'YYYY-M-D H:m');//Because you are using numbers/integers, none of them will have preceding zeroes
Take a look at the Date constructor - I think it doesn everything you need.
Your biggest gotcha is that months are 0-indexed so you'll actually turn 9 into October. Also beware that if you don't initialise Date with anything, it'll assume you mean now.
var date = new Date();
date; // -> Tue Oct 17 2017 13:34:49 GMT+0100 (GMT Daylight Time)
date.setMonth(10); // -> 1510925689970
date; // -> Fri Nov 17 2017 13:34:49 GMT+0000 (GMT Standard Time)

How To add number of month into the given date in javascript?

I want to add month into the select date by the user.
startdate=document.getElementById("jscal_field_coverstartdate").value;
now I want to add 11 month from the above startdate. How to do that.
date format = 2013-12-01
Without the date format it is difficult to tell, however you can try like this
add11Months = function (date) {
var splitDate = date.split("-");
var newDate = new Date(splitDate[0], splitDate[1] - 1, splitDate[2]);
newDate.setMonth(newDate.getMonth() + 11);
splitDate[2] = newDate.getDate();
splitDate[1] = newDate.getMonth() + 1;
splitDate[0] = newDate.getFullYear();
return startdate = splitDate.join("-");
}
var startdate = add11Months("2013-12-01");
alert(startdate)
JSFiddle
If your startdate is in correct date format you can try using moment.js or Date object in javascript.
In Javascript, it can be achieved as follow:
var date = new Date("2013-12-01");
console.log(date);
//output: Sun Dec 01 2013 05:30:00 GMT+0530 (India Standard Time)
var newdate = date.setDate(date.getDate()+(11*30));
console.log(new Date(newdate));
// output: Mon Oct 27 2014 05:30:00 GMT+0530 (India Standard Time)
In above lines, I have used 30 days per month as default. So you will get exact 11 month but little deviation in date. Is this what you want ? You can play around this likewise. I hope it help :)
For more about Date you can visit to MDN.
You can do it like this:
var noOfMonths = 11
var startdate = document.getElementById("jscal_field_coverstartdate").value;
startdate.setMonth(startdate.getMonth() + noOfMonths)
Try this:
baseDate.setMonth(2);
baseDate.setDate(30);
noMonths = 11;
var sum = new Date(new Date(baseDate.getTime()).setMonth(baseDate.getMonth() + noMonths);
if (sum.getDate() < baseDate.getDate()) { sum.setDate(0); }
var m = newDate.getDate();
var d = newDate.getMonth() + 1;
var yyyy = newDate.getFullYear();
return (yyyy+"-"+m+"-"+d);
Notes:
Adding months (like adding one month to January 31st) can overflow the days field and cause the month to increment (in this case you get a date in March). If you want to add months and then overflow the date then .setMonth(base_date.getMonth()+noMonths) works but that's rarely what people think of when they talk about incrementing months.
It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow
Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.

Javascript DATE add AM PM

I am doing a check of two different date times to see if one is greater than the other:
Here is my (now) current date time: Thu Aug 01 2013 10:27:40 GMT-0500 (CDT)
And here is my date time that I am seeing if it is greater or less than: Thu Aug 01 2013 12:15:00 GMT-0500 (CDT) - (that should be 12:15 am by the way)
Here is my code:
var current_date_time = new Date();
var date_time_checking_against = new Date(date_segment[0], date_segment[1]-1, date_segment[2], time_segment[0], time_segment[1]);
Which comes out to Thu Aug 01 2013 12:15:00 GMT-0500 (CDT). And then I am doing a simple if check:
if(current_date_time >= date_time_checking_against){ }
This is not working as 10:27:40 is not after 12:15:00. But it should be, seeing as how both times are AM. I need to know if this is the right way, or if there is a way to change it to 24 hour format or add am pm in there somehow. Any help is greatly appreciated, let me know if you need more clarity.
Thanks!
EDIT:
Here is the date time array:
var date_time_str = date+' '+time;
date_time_str = date_time_str.split(' ');
["2013-08-01", "12:15", "am"] // result from split above
var date_segment = date_time_str[0].split('-');
var time_segment = date_time_str[1].split(':');
var date_time_checking_against = new Date(date_segment[0], date_segment[1]-1, date_segment[2], time_segment[0], time_segment[1]);
Given the following data sources, this is how you'd properly create the Date object for it...
date_time_str = ["2013-08-01", "12:15", "am"];
var date_segment = date_time_str[0].split('-');
var time_segment = date_time_str[1].split(':');
var date_time_checking_against = new Date(
date_segment[0], // year
date_segment[1]-1, // month of year
date_segment[2], // day of month
(time_segment[0]%12) + (date_time_str[2] == 'pm' ? 12 : 0), // hour of day
time_segment[1]); // minute of hour
console.log(new Date() >= date_time_checking_against); // true, we've already passed this time

Getting current time from the date object

function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0].substring(2), // get only two digits
month = datePart[1], day = datePart[2];
document.write(new Date(day+'/'+month+'/'+year));
}
formatDate ('2010/01/18');
When i print this i get Thu Jun 01 1911 00:00:00 GMT+0530 (India Standard Time) but the system is actually 3:42 P.M
Use the current date to retrieve the time and include that in the new date. For example:
var now = new Date,
timenow = [now.getHours(),now.getMinutes(),now.getSeconds()].join(':'),
dat = new Date('2011/11/30 '+timenow);
you must give the time:
//Fri Nov 11 2011 00:00:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11"));
//Fri Nov 11 2011 23:23:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11 23:23"));
What do you want? Just the time? Or do you want to define a format? Cu's the code expects this format for date: dd/mm/yyyy, changed this to yyyy/mm/dd
Try this:
function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0],
month = datePart[1], day = datePart[2],
now = new Date;
document.write(new Date(year+'/'+month+'/'+day+" " + now.getHours() +':'+now.getMinutes() +':'+now.getSeconds()));
}
formatDate ('2010/01/18')
Output:
Mon Jan 18 2010 11:26:21 GMT+0100
Passing a string to the Date constructor is unnecessarily complicated. Just pass the values in as follows:
new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10))
You're creating a Date() object with no time specified, so it's coming out as midnight. if you want to add the current date and time, create a new Date with no arguments and borrow the time from it:
var now = new Date();
var myDate = new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10),
now.getHours(), now.getMinutes(), now.getSeconds())
No need to strip the last two characters off the year. "2010" is a perfectly good year.

Categories

Resources