Javascript Date string constructing wrong date [duplicate] - javascript

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"

Related

Validate if string is a date [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
How to validate a date?
(11 answers)
Closed 2 years ago.
I've seen many articles about this but not quite found what I am looking for yet.
I'm trying to simply check if a string is a date. That string might contains a number such as 2012 though.
var timestamp = Date.parse('foo 2012');
if (isNaN(timestamp) == false) {
var d = new Date(timestamp);
console.log('DATE', d)
}else{
console.log('TEXT');
}
//OUTPUT: DATE Sun Jan 01 2012 00:00:00 GMT+1100 (Australian Eastern Daylight Time)
Why does javascript convert foo 2012 into a date when it's clearly not?
How can I validate that my string is an actual date ?
A string is never a date.
A string can represent a date. There are many ways to represent the same date through different string formats.
This means "validating that a string is a date" is an impossible task. What you can do instead is:
Validate that the format of the string conforms to some well-known format and that its contents are valid.
Try to parse a given string as an expected format and either throw an error or return a "guard" value to indicate that the parsing was not a success.
JavaScript took a third option, which is like option 2, only it returns a value indicating its "best efforts" at working with the garbage input. That's apparently why it saw a year in your string and decided "well, I guess I can make a date with this?" As #Pointy pointed out, it's actually in the spec that if the JavaScript string doesn't match one of the two supported formats, the implementer can decide what the result should be.
I'd highly recommend that if you're dealing with date strings, you should stick with a consistent format. I'm a big fan of ISO 8601 date/time strings because they are time zone aware, easy to sort, and are widely supported (including being easily parsed by JavaScript). If you're requiring the strings are in a standard format, it's easier to do things like finding A RegExp that can validate the input.

Incorrect date being set with new Date() [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 5 years ago.
When using the below line I am expecting the result to be '22/09/2017 14:05:43', however it is actually returning '09‎/‎10‎/‎2018‎ ‎14‎:‎05‎:‎43'.
var theDate = new Date('22/09/2017 14:05:43').toLocaleString();
I know there are js libraries out there such as moment.js that can be used for a lot of date time manipulation, but I was just wondering if anyone knew why this was happening and how I can get this to return the expected date?
Parsing of date strings is mostly implementation dependent, so it's generally recommended to avoid the built-in parser. Most browsers treat JavaScript dates with a pattern xx/xx/xxxx as MM/DD/YYYY, so 22/09/2017 is seen as either an invalid date (e.g. Safari, Firefox, Chrome), or the 9th day of the 22nd month of 2017 (apparently your browser).
Your browser is interpreting it as 'the 9th day of the 22nd month', so you're ending up on October 9th 2018, 22 months and 9 days into 2017.
To resolve this, you can separate the string into parts and give them to the constructor, avoiding the built-in parser (remembering to subtract 1 from the month number):
new Date(2017, 8, 22, ...)
Refer to MDN's Date documentation for more information.
Well the initial date string you passed to the Date constructor is wrong, it should be in the format 'MM/DD/YYYY HH:mm:ss'.
Your actual code will give Invalid Date:
var theDate = new Date('22/09/2017 14:05:43');
console.log(theDate);
var str = theDate.toLocaleString();
console.log(str);
Here 22 will be treated as a month and 09 will be treated as day. You need to fix it so it follows the Date standards:
var theDate = new Date('09/22/2017 14:05:43');
console.log(theDate);
var str = theDate.toLocaleString();
console.log(str);

Javascript getFullYear() returns the wrong year [duplicate]

This question already has answers here:
JavaScript's getDate returns wrong date
(12 answers)
Closed 6 years ago.
This is so basic, but it makes no sense to me:
new Date("2010-01-01").getFullYear();
result: 2009
wth? My goal is to reformat the date as mm/dd/yyyy given the format yyyy-mm-dd..
Adding on:
new Date("2010-01-01").getMonth();
result: 11
new Date("2010-01-01").getDate();
result: 31
The date string you're passing into new Date() has no timezone in it. It's being interpreted as UTC. The critical thing to understand here is that a Date is stored as a Unix timestamp (seconds since 1970-01-01 00:00, making 'Date' a misleading name) so if you don't specify the time within the date, it's going to apply a default.
Date.prototype.getFullYear() retrieves the full year for that timestamp in your LOCAL time. (See the docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear)
You're somewhere west of UTC, and 2010-01-01 UTC is 2009-12-31 in your local time.
And for your final mystery....getMonth() is 0-based, not 1-based, so '11' is December.
Don't use the Date constructor to parse strings, it's largely implementation dependent and inconsistent.
An ISO 8601 date and time without a timezone like "2016-02-29T12:00:00" should be treated as local (i.e. use the host system timezone offset to create a Date), but a date–only string is treated like "2016-02-29" as UTC. The first behaviour is consistent with ISO 8601, but the second isn't.
Some versions of browsers will treat date–only strings as UTC, and some as invalid dates, so always parse strings manually (a two line function or library can help). That way you know how it will be parsed in all hosts.
Provide Time with date in the new Date() as parameter . Then u will get exact Result.

Why does a string of numbers work differently than actual numbers in a new Date?

Why does a string of numbers work differently than actual numbers in a new Date():
var myfirstDate = new Date("2013, 10, 15"); //returns Tue Oct 15 2013 00:00:00 GMT-0500 (CDT)
var mysecondDate = new Date(2013, 9, 15); // also returns Tue Oct 15 2013 00:00:00 GMT-0500 (CDT)
myfirstDate.value == mysecondDate.value; //returns true
I looked at several tutorials and the idea of having a string like myfirstDate above isn't even mentioned. Does javascript automatically parse the string?
See the docs.
You're effectively invoking two different constructors.
The first one is parsed as a human-readable date:
new Date(dateString)
The second one expects 3 or more parameters, providing a year, a 0-based month number, and a day
new Date(year, month, day [, hour, minute, second, millisecond]);
year
Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998, rather than 98.
month
Integer value representing the month, beginning with 0 for January to 11 for December.
day
Integer value representing the day of the month (1-31).
Until ES5, parsing of date strings was entirely implementation dependent, though there were one or two strings that were consistently parsed by several browsers. ES5 introduced parsing of a version of ISO8601, however it's not supported by all browsers in use.
It is best to manually parse date string to ensure they are correct. There are various libraries to assist with that, but it isn't difficult (2 lines of code).
Incidentally, there is no Date.prototype.value method, so likely you are comparing undefined with itself. You should be comparing the time value, so:
myfirstDate.getTime() == mysecondDate.getTime();
or just:
myfirstDate == mysecondDate;
Oh, to answer the question: when the Date function is called as a constructor with a single string argument, it is treated as a date string and parsed (see above). So "10" represents October.
When Date is called as a constructor with more than one argument, they are treated as date values so 9 is treated as October since month arguments are zero indexed (0=January, 1=February, etc.).

Extracting date strings from the JavaScript Date object without timezones being applied

I want to do a straight conversion of a date string and cannot get the results I expect. I expect the below code to produce a date equal to the date portion of the original string, but it seems to apply a time during the instance creation.
var usageTime = new Date('2012-01-19T22:59:50-0800');
console.log(usageTime); // Fri, 20 Jan 2012 06:59:50 GMT
dayOfUsage = usageTime.getFullYear()+'-'+(usageTime.getMonth()+1)+'-'+usageTime.getDate();
console.log(dayOfUsage); // 2012-1-20
I expect a date of 2012-1-19. What is the right way to solve this?
You should use getUTC*() functions (getUTCDate(), getUTCHours() and so on) to get your times with no timezone offset.

Categories

Resources