Converting date string to Date() adds a month [duplicate] - javascript

This question already has answers here:
javascript date conversion showing wrong month
(3 answers)
javascript is creating date wrong month
(4 answers)
Closed 2 years ago.
Ok, I have a weird issue. I'm just starting with Node and MongoDB and at first I got a little bit confused by the whole ISO time vs local time and I ran into a weird issue.
I got a string with a date, and although it's overkill, I manually splitted it and pass it to the "new Date()" constructor, it adds one month to all the dates.
This is my code:
str = str.split(' ')
str[0] = str[0].split('-')
str[1] = str[1].split(':')
console.log(str)
str = new Date(str[0][0],str[0][1],str[0][2],str[1][0],str[1][1],str[1][2]);
console.log(str)
console.log(str.toString())
And this is the output:
[ [ '1970', '01', '01' ], [ '00', '00', '00' ] ] //First UNIX date splitted into a yyyy, mm, dd, HH, MM, DD
1970-02-01T03:00:00.000Z //After the Date object is generated, note that the month is now "02"
Sun Feb 01 1970 00:00:00 GMT-0300 (hora de verano de Chile) //The date returned to local time. Note that the month change was maintained.
Am I doing something wrong in changing types? Does it have to do with something aside the code?
The whole purpose is to insert the Date object into a mongodb collection in ISO format, and then query it back and show it in local time.

According to the documentation for Date, the month is zero-indexed. So it's not adding a month, you're just passing the wrong value because the month in your string is one-indexed.
Subtract 1 from that value:
new Date(str[0][0], str[0][1] - 1, str[0][2], str[1][0], str[1][1], str[1][2]);

Related

How can I convert this string to a date? [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 10 months ago.
I need to convert string "Apr 28 2022 12:00AM" to date. I have tried Date.parse, but it is returning "Nan".
var dtstring = "Apr 28 2022 12:00AM";
var dt = Date.parse(dtstring);
console.log(dt);
On the MDN documentation page it is said:
The ECMAScript specification states: If the String does not conform to
the standard format the function may fall back to any
implementation–specific heuristics or implementation–specific parsing
algorithm. Unrecognizable strings or dates containing illegal element
values in ISO formatted strings shall cause Date.parse() to return
NaN.
So the date format is as follows
if we correct and write the code is working
var dtstring = "Apr 28 2022 12:00";
var dt = Date.parse(dtstring);
console.log(dt);
If you can change the string of the date, you could just use the Date constructor: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
So for example:
new Date('2022-04-28T12:00:00');
But if you can't change the string, you'll have to use a javascript library that can parse this date.
Here is an example with date-fns and it's function parse:
parse('Apr 28 2022 12:00 AM', 'MMM dd yyyy p', new Date());
Here is the link of the documentation: https://date-fns.org/v2.28.0/docs/parse

JavaScript: get first and last day of month with format YYYY.MM.DD [duplicate]

This question already has answers here:
Get String in YYYYMMDD format from JS date object?
(53 answers)
Closed 6 years ago.
I'm trying to get the first and last day of the month with the format 2016.02.29, but I'm not sure how to turn the date into this format.
The following code (taken from here):
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
Gives this format: Mon Feb 29 2016 00:00:00 GMT+0100 (W. Europe Standard Time).
How do i make it look like 2016.02.29? I could manipulate the string to get the result I want, but isn't there a way to get it by just defining a format?
You can use the MomentJs to format any date by specifying the exact format.
Load the momentjs or momentjs + locale script in your page
moment().format('YYYY.MM.DD');

Javascript Date string constructing wrong date [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
Hi I am trying to construct a javascript date object with a string, but it keeps contructing the wrong day. It always constructs a day that is one day behind. Here is my code
var date = new Date('2006-05-17');
The date i want to get is
Wednesday May 17 2006 00:00:00 GMT-0700 (PDT)
But instead I get
Tue May 16 2006 17:00:00 GMT-0700 (PDT)
When you pass dates as a string, the implementation is browser specific. Most browsers interpret the dashes to mean that the time is in UTC. If you have a negative offset from UTC (which you do), it will appear on the previous local day.
If you want local dates, then try using slashes instead, like this:
var date = new Date('2006/05/17');
Of course, if you don't have to parse from a string, you can pass individual numeric parameters instead, just be aware that months are zero-based when passed numerically.
var date = new Date(2006,4,17);
However, if you have strings, and you want consistency in how those strings are parsed into dates, then use moment.js.
var m = moment('2006-05-17','YYYY-MM-DD');
m.format(); // or any of the other output functions
What actually happens is that the parser is interpreting your dashes as the START of an ISO-8601 string in the format "YYYY-MM-DDTHH:mm:ss.sssZ", which is in UTC time by default (hence the trailing 'Z').
You can produce such dates by using the "toISOString()" date function as well.
http://www.w3schools.com/jsref/jsref_toisostring.asp
In Chrome (doesn't work in IE 10-) if you add " 00:00" or " 00:00:00" to your date (no 'T'), then it wouldn't be UTC anymore, regardless of the dashes. ;)
Remove the prepending zero from "05"

Javascript Date shows the wrong value when using alert [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript is creating date wrong month
In my code, I create Date by this line:
var date = new Date('2012', '01', '20')
and then using:
alert(date);
I get the result:
I don't really understand why not Jan instead of Feb?
jsFiddle: http://jsfiddle.net/U5m8N/
The "Month" part of var date = new Date('2012', '01', '20'); is zero-indexed.
Start counting at 0, and you got your month. (So, January is 0, Feb 1, etc.)
Also, while JavaScript does accept strings as parameters, you should be using integers, as the documentation suggests:
Date Documentation
Javascript Date Object's Month is 0 indexed. http://www.w3schools.com/jsref/jsref_obj_date.asp. put 0 instead of 1 for Jan

Adding one day to Javascript date + unique formatting?

I've inherited a project for a company I'm working for. Their dates are recorded in the following format:
March 18th, 2011 would be listed as "18 Mar 2011".
April 31st, 2010 would be listed as "31 Apr 2010".
How would I use Javascript to add one day to a date formatted in the above manner, then reconvert it back into the same format?
I want to create a function that adds one day to "18 Mar 2011" and returns "19 Mar 2011". Or adds 1 day to "30 Jun 2011" and returns "1 Jul 2011".
Can anyone help me out?
First of all there is no 31st of April ;)
To the actual issue, the date object can understand the current format when passed as an argument..
var dateString = '30 Apr 2010'; // date string
var actualDate = new Date(dateString); // convert to actual date
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1); // create new increased date
// now extract the bits we want to crete the text version of the new date..
var newDateString = ('0'+newDate.getDate()).substr(-2) + ' ' + newDate.toDateString().substr(4,3) + ' ' + newDate.getFullYear();
alert(newDateString);
demo at http://jsfiddle.net/gaby/jGwYY/1/
The same extraction using (the better supported) slice instead of substr
// now extract the bits we want to crete the text version of the new date..
var newDateString = ('0'+newDate.getDate()).slice(-2) + ' ' + newDate.toDateString().slice(4,7) + ' ' + newDate.getFullYear();
Demo at http://jsfiddle.net/jGwYY/259/
You would want to convert the date string into a Date object, add one day to the object, and then convert back. Please have a look at the API docs for Date as a starting point.
Most (all?) browsers will be able to parse that date string in with a simple
var parsedDate = new Date(dateString);
Once you have a Date object you can add a day and output a formatted date string using something like underscore.date.
If you discover that some browsers can't parse that date format then you can write a pretty simple regex that will pull apart the date string into its constituent parts, and then build a Date instance by hand.
Also I would strongly recommend doing the parsing in a separate function, and to try and keep dates in a Date representation as much as possible. Parse the string into a date as soon as you can, and format it back into a string as late as you can.

Categories

Resources