Javascript newdate function unexpected output - javascript

I am confused by the result of the following script and I don't understand why it is what it is:
enddate = '01-02-2020'; //euro format dd-mm-yyyy
datesplit = enddate.split("-");
console.log("datesplit: ", datesplit); //[ '01', '02', '2020' ]
console.log(datesplit[2]); // 2020
console.log(datesplit[1]); // 02
console.log(datesplit[0]); // 01
enddate1 = new Date(datesplit[2],datesplit[1],datesplit[0]);
console.log("enddate 1", enddate1); //output: 2020-03-01T05:00:00.000Z , but I'm expecting 2020-02-01T00:00:00.000Z
That last console log output is what I can't understand. I would appreciate an explanation of why the result is what it is.

JavaScript treats the month as zero-based. So you'll have to -1 your month value to get the right result. As #RobG said, you should use new Date(Date.UTC(...)) to get your date in UTC
let endDate = '01-02-2020' // dd-mm-yyyy;
let [day, month, year] = endDate.split('-');
// Months are zero-based, so -1 to get the right month
month = month - 1;
console.log(day); // '01'
console.log(month);// 1
console.log(year); // '2020'
let newDate = new Date(Date.UTC(year, month, day));
console.log(newDate) // "2020-02-01T00:00:00.000Z"

Given that the other posts seem to have helped you get the right month, have you tried using .toISOString method on the Date object to get the right UTC offset?
The docs on MDN state that the timezone is always zero UTC offset.

You can check Mozilla Documentation
You will see that January is 0, February is 1, and so on. So that's how date works in JavaScript.
You need to convert your month value to Number and then make it "-1". So something like this:
new Date(datesplit[2], (parseInt(datesplit[1], 10) - 1), datesplit[0])

Related

How to get previous date in javascript

I have one date but i want to get previous date from that.How we can do using javascript or momentjs?
Demo:https://stackblitz.com/edit/js-ykswiz?file=index.js
date format dd-mm-yyyy.
Example:
var date1=new Date("08-06-2020");
console.log("Prev Date="+date1.getDate() - 1);// Prev Date=07-06-2020
var date2=new Date("01-06-2020");
console.log("Prev Date="+date2.getDate() - 1);// Prev Date=31-05-2020
var date3=new Date("01-01-2021");
console.log("Prev Date="+date3.getDate() - 1);// Prev Date=31-12-2020
Is it possible in javascript?
first, if you pass a string to the new Date() function, it should be in this format new Date('MM-dd-yyyy')
so the first 2 digits represent the month
the second 2 digits represent the date
the next 4 digits represent the year
so new Date("08-06-2020") means August 06, 2020 not June 08, 2020
to get the previous day of some date, we can use the moment to subtract 1 day like the following
var date1 = new Date('08-06-2020'); // Aug 06, 2020
var date11 = moment(date1).subtract(1, 'days').format('DD-MM-YYYY');
console.log(`date1 >> ${date1}`);
console.log(`date11 >> ${date11}`);
var date2 = new Date('01-06-2020'); // Jan 06, 2020
var date22 = moment(date2).subtract(1, 'days').format('DD-MM-YYYY');
console.log(`date2 >> ${date2}`);
console.log(`date22 >> ${date22}`);
hope it helps
Since the issue with the Date constructor is explained and solved by one of the above answers, this solution is for the ones who use moment() instead of new Date() 👇
var date = moment('08-06-2020', 'DD-MM-yyyy');
var previousDate = moment(date).subtract(1, 'days'); //derive the previous date
var nextDate = moment(date).add(1, 'days'); //derive the next date
console.log(previousDate.format('DD-MM-yyyy')); //output => 07-06-2020
console.log(nextDate.format('DD-MM-yyyy')); //output => 09-06-2020
👇 read more about adding and subtracting dates in moment.js
https://momentjs.com/docs/#/manipulating/subtract/
https://momentjs.com/docs/#/manipulating/add/
👇 read more about formatting dates in moment.js
https://momentjs.com/docs/#/parsing/string-format/
you can use the setDate and getDate functions;
var date1=new Date("08-06-2020");
date1.setDate(date1.getDate() - 1);
console.log("Prev Date="+date1.getDate());// Prev Date=08-05-2020
hope its what you asked for.
btw, in this format tha previous date will be 08-05-2020 since the default is mm-dd-yyyy
You could achieve this using momentjs. Use the moment constructor to parse the input string then use the subtract() to subtract the specified number of days from the moment object. Resultant can be formatted according to your requirements
let arr = ["08-06-2020", "01-06-2020", "01-01-2021"];
let prevDates = arr.map(item => {
let momentItem = moment(item, "DD-MM-YYYY");
let prevDay = momentItem.subtract(1, "days");
return prevDay.format("DD-MM-YYYY");
});
console.log(prevDates);
<script src="https://momentjs.com/downloads/moment.js"></script>

Javascript and setMonth behaving unexpectedly

I am doing datObj.setMonth(1), but the month is being set to March? Isn't 1 supposed to be February? I'm using Chrome 79.
Here's part of code meant to parse dates such as YYYY-MM-DD HH:MM:SS (because safari can't do that natively)
var date = "2020-02-02 23:59:00"
if (typeof date == 'string')
{
var dateParts = date.split(/[:-\s]+/);
if (dateParts.length == 6)
{
dateObj = new Date();
dateObj.setYear(dateParts[0]);
var m = dateParts[1] - 1;
console.log('m= ' + m);
dateObj.setMonth(m);
console.log('after setmonth, date= ' + dateObj);
dateObj.setDate(dateParts[2]);
dateObj.setHours(dateParts[3]);
dateObj.setMinutes(dateParts[4]);
dateObj.setSeconds(dateParts[5]);
}
}
console.log(dateObj);
alert(dateObj);
Your problem, as you figured, is that you're setting the month while the day is still 30. While you could work around that by using setFullYear and pass year, month and day at once, you really should just construct the whole Date object with the right values in the first place:
dateObj = new Date(dateParts[0], dateParts[1]-1, dateParts[2], dateParts[3], dateParts[4], dateParts[5]);
or rather using UTC as the timezone:
dateObj = new Date(Date.UTC(dateParts[0], dateParts[1]-1, dateParts[2], dateParts[3], dateParts[4], dateParts[5]));
Just figured this out before I submitted. Today is January 30th, 2020. I can't change the month to February, because there is no February 30th. So, the code breaks either on the 29th or the 30th day of the month.
In JavaScript, it is advisable to do
dateObj.setMonth(monthNum -1, dayNum)
to set the day and month at the same time to avoid this problem

Javascript Date working strange

I was working with Javascript Date and faced strange problem.
date1 = new Date(1970, 1, 1);
date2 = new Date("1970-01-01T13:00:00.000Z");
console.log(date1.getYear()); //70
console.log(date1.getMonth()); //1
console.log(date1.getDay()); //0 expect 1
console.log(date2.getYear()); //70
console.log(date2.getMonth()); //0 expect 1
console.log(date2.getDay()); //4 expect 1
Why this result happened? What I am doing wrong with Date Object?
FIDDLE
UPDATE:
console.log(date1);
shows this result.
Date 1970-01-31T14:00:00.000Z
With new Date(year, month, date), month is 0 based, so 1 is not January but february, so your date1 and date2 are different dates. Then, the function getDay returns 0 to 6, that corresponds to Monday to Sunday. If you want the date, you have to use getDate instead.

Issue with converting string which is of DateTime to javascript Date

I have a string which contains DateTime as "20140121230000" . If i try to convert this into a Date.
var oDate = new Date(20140121230000);
i'm getting the year as 2068! Is there a way to convert this into a Date which is of year 2014, month 01 Date 21 Time 23:00:00 ?
Is it possible to directly convert this without doing any parsing in the string ?
Unless you use a library there is no way to convert the value without manually splitting the string.
var year = +oDate.slice( 0, 4);
var month = +oDate.slice( 4, 2) - 1; // Month is zero-based.
var day = +oDate.slice( 6, 2);
var hour = +oDate.slice( 8, 2);
var minute = +oDate.slice(10, 2);
var second = +oDate.slice(12, 2);
// This will interpret the date as local time date.
var date = new Date(year, month, day, hour, minute, second);
// This will interpret the date as UTC date.
var utcDate = Date.UTC(year, month, day, hour, minute, second);
The constructor you used takes millisecond since 1st Jan, 1970, try using :
var oDate = new Date(2014, 01, 21, 23, 00, 00, 00);
Note, month 01 will be Feb, not Jan.
Constructing a Date object with a string
new Date(string)
expects a date string that Date.parse can understand:
ISO 8601 (e.g. 2011-10-10T14:48:00), or
RFC2822 (e.g., Mon, 25 Dec 1995 13:30:00 GMT)
See MDN for more information on Date and Date.parse.
Yours is not a recognized format. You can either
reformat the string to fit one of the formats above
split the string manually and call Date with individual parameters, as in new Date(year, month, day, hour, minute, second, millisecond)
use a library like moment.js
Using moment.js would look something like this:
moment("20140121230000", "YYYYDDMMHHmmss")
See moment.js string + format for more information about the format syntax.
Given '20140121230000', you can split it into bits and give it to the Date constructor:
function parseSToDate(s) {
var b = s.match(/\d\d/g) || [];
return new Date( (b[0] + b[1]), --b[2], b[3], b[4], b[5], b[6]);
}
console.log(parseSToDate('20140121230000'));

What is the proper way to create a timestamp in javascript with date string?

I have date format returned as 05-Jan, 12-feb etc.. when i convert current date using date object in javascript . I did something like this
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDay(),
today = new Date(curr_year, curr_month, curr_day, 0, 0, 0, 0);
console.log(today);
Here the today is returned as invalid date i needed the create a timestamp which should not include minutes secs and millisecs as zero for date comparison of month and date alone based on that i can categories .Is there way to dynamically create a date and compare those dates for given format.
And when i try to convert my date string using date object it returns year as 2001. how can i compare dates based upon current year.
For eg: in php i have used mktime to create a date dynamically from given date format and compare those results. Any suggestion would be helpful. Thanks.
You can leverage the native JS Date functionality to get human-readable date strings for time stamps.
var today = new Date();
console.log( today.toDateString() ); // Outputs "Mon Feb 04 2013"
Date comparison is also built in.
var yesterday = new Date();
yesterday.setDate( yesterday.getDate() - 1);
console.log( yesterday.toDateString() ); // Outputs "Sun Feb 03 2013"
console.log( yesterday < today ); //Outputs true
You can use the other built-in methods to fine-tune this comparison to be/not be sensitive to minutes/seconds, or to set all those to 0.
You said that you used mktime() in php, so what about this?
change to this :
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth()+1,
curr_day = curr.getDay(),
today = curr_month+'/'+curr_day+'/'+curr_year;
console.log(today);
(getMonth()+1 is because January is 0)
change the :
today = curr_month+'/'+curr_day+'/'+curr_year;
to whatever format you like.
I have found a way to convert the date into timestamp i have tried as #nbrooks implemented but .toDateString has built in date comparison which works for operator < and > but not for == operator to do that i have used Date.parse(); function to achieve it. Here it goes..
var curr = new Date(),
curr_year = curr.getFullYear(),
curr_month = curr.getMonth(),
curr_day = curr.getDate(),
today = new Date(curr_year, curr_month, curr_day, 0,0,0,0);
var dob = new Date('dob with month and date only'+curr_year);
if(Date.parse(dob) == Date.parse(today)){
//Birthdays....
}
This method can be used to create a timestamp for dynamically created date.Thanks for your suggestions.

Categories

Resources