moment.js not accepting "31\\Oct\\2016" as a date - javascript

Cant seem to figure why this works
moment("30\\Nov\\2016 22:14","DD\\MM\\YYYY HH:mm").toString()
(The result is "Wed Nov 30 2016 22:14:00 GMT+0000")
and this does not work
moment("31\\Oct\\2016 22:14","DD\\MM\\YYYY HH:mm").toString()
(The result is "Invalid date").
Does anybody have any idea why this is happening?
edit
changed the date above
edit 2
tried this snippet
moment("30\\Jan\\2016 22:14","DD\\MMM\\YYYY HH:mm").toString()
result = "Wed Nov 30 2016 22:14:00 GMT+0000"
thats strange

A couple of issues here:
Firstly your date format using backslashes is causing a problem (single or double backslashes both cause different issues) in certain instances. I'm not sure exactly what the issue is, since the first example works, but I suspect it's treating it as some sort of escape sequence.
Secondly, "MM" is the wrong token to use to parse short month names. It should be "MMM". It seems coincidence that it works for your "Nov" string when using "MM", but it certainly doesn't work for "Oct" or most others.
If you can change your data source to provide dates using a different separator (/ or - are pretty standard) then do that. If not, you might have to do a string replace on the date string just before you feed it to momentJS.
Examples of strings that don't work (either produce incorrect dates, or report "Invalid Date"):
"31\\Oct\\2016 22:14","DD\\MMM\\YYYY HH:mm"
"31\Oct\2016 22:14","DD\MMM\YYYY HH:mm"
"31/Oct/2016 22:14","DD/MM/YYYY HH:mm"
As you can see, it's evolved almost to the point of a parseable string, which would look like:
"31/Oct/2016 22:14","DD/MMM/YYYY HH:mm"

Related

Convert java date into angular date

I am working on project uses angular4(frontend) and java(backend).
I get the date in below format from java backend server into angular server.
2018-05-23T18:30:00.000+0000
I need to convert it into javascript/angular Date object.
I have tried below code
Date d = new Date(java_date);
but this gives Invalid Date error.
Any idea how to deal with above date format.
The string "2018-05-23T18:30:00.000+0000" is not consistent with the format in ECMA-262, it's missing colon in the timezone offset between the hours and minutes, so implementations may treat it as invalid (e.g. Safari).
You have a number of options:
Replace the timezone offset with "Z" and use the built–in parser: new Date('2018-05-23T18:30:00.000Z')
Insert a colon in the offset and use the built–in parser: new Date('2018-05-23T18:30:00.000+00:00')
Write your own parser for this particular format (maybe 4 lines of code)
Use a library (there are many good ones and they can help with formatting too)
I'd recommend either 3 or 4 as the built–in parser is notoriously fickle, but any of the above will likely do.
The Date as you wrote it - given by its ISO string, you should parse it using JS/Angular
var a = Date.parse("2018-05-23T18:30:00.000+0000");
Here's a relevant link to MDN :
MDN Parse
MDN ISO

Parse Date "01/01/2016 Fri"

I am trying to parse a date in JavaScript, but the particular format is giving me fits. I have exported data from my credit card company and the format of the date field is not compatible with Date.parse or moment().isValid().
E.g.
Date.parse("01/01/2016 Fri") // NaN
moment("01/01/2016 Fri") // false
I'm not sure if I should do something with a RegEx .test() or .matches() because this is being used for a CSV import utility where dates may be in different formats. I was surprised the utility functions above didn't work.
Look in the Moment docs to see how to parse a date in any format. The first argument is the date string, the second is the format string. Alphanumeric characters are ignored, so you don't need to worry about slashes vs. dashes.
moment("01/01/2016 Fri", "MM-DD-YYYY ddd)
Check out the Mozilla MDN on Date.parse():
The parse() method takes a date string (such as "Dec 25, 1995") and
returns the number of milliseconds since January 1, 1970, 00:00:00
UTC. This function is useful for setting date values based on string
values, for example in conjunction with the setTime() method and the
Date object.
Given a string representing a time, parse() returns the time value. It
accepts the RFC2822 / IETF date syntax (RFC2822 Section 3.3), e.g.
"Mon, 25 Dec 1995 13:30:00 GMT". It understands the continental US
time zone abbreviations, but for general use, use a time zone offset,
for example, "Mon, 25 Dec 1995 13:30:00 +0430" (4 hours, 30 minutes
east of the Greenwich meridian).
From this, it looks like your problem is that you're giving the date in the improper format:
It
accepts the RFC2822 / IETF date syntax (RFC2822 Section 3.3), e.g.
"Mon, 25 Dec 1995 13:30:00 GMT".
Check this out:
Invalid values in date strings not recognized as ISO format as defined by ECMA-262 may or may not result in NaN, depending on the browser and values provided, e.g.:
// Non-ISO string with invalid date values
new Date('23/25/2014');
TL;DR - you're passing the values in a format that is not recognized, which is why it's returning NaN.
Try this source for Regexes for dates: Regexlib.com. The site is a little out of date, but the info is great. It has tons of different Regexes for different date formats.

(new Date('2012-12-01')).getMonth() === 10?

(new Date('2012-12-01')).getMonth() is 10 instead of 11 (getMonth is 0-indexed). I've tested on Firefox, Chrome, and Node.js. Why does this happen?
You are experiencing a timezone issue. Your JS engine interprets the string as UTC, since it was no further specified. From the specification of Date.parse (which is used by new Date):
The String may be interpreted as a local time, a UTC time, or a time in some other time zone, depending on the contents of the String. The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
In your timezone, the datetime is Nov 30 2012 19:00:00 GMT-0500 - in November. Use .getUTCMonth() and you would get December. However, never trust Date.parse, every browser does it differently. So if you are not in a restricted environments like Node.js, you always should parse your string (e.g. with regex) and feed it to new Date(Date.UTC(year, month, date, …)).
For Firefox's case, at least, RFC2822 states that date specifications must be separated by Folding White Space. Try (new Date('2012 12 01')).getMonth(); Usage of - as a separator does not appear to be defined.
The error is arising from prefixing the day 01 with 0. Not sure WHY this is, but if you remove the zero before the 1, it gives you the right month (11).
Also, it starts giving the wrong month at October if that means anything.
Short term fix, use 1 instead of 01.

Possible return values for (new Date()).toDateString() in JavaScript?

The return value for (new Date()).toDateString() is "Mon Oct 08 2012". However I can't find ANY documentation anywhere for what the abbreviations for the rest of the days of the week and months are. Are they all just 3 character abbreviations? I'm trying to write a regex.
+1million points for someone who can find the documentation, or even the source code?
Three letter abbreviations with the first letter upper case.
Months: Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
Days: Sun, Mon, Tue, Wed, Thu, Fri, Sat
However, you may want to look into Date.Parse() instead of using a regular expression to parse the date string, depending on what you're doing anyway.
EDIT: Beware that that Date.Parse() is fairly browser dependent. Check out Why does Date.parse give incorrect results?
It's just the standard English language abbreviation for days and months. Just the first 3 letters and the first one capitalized.
From the MDN:
Date instances refer to a specific point in time. Calling toString
will return the date formatted in a human readable form in American
English
It's not hard to find:
W3Schools: http://www.w3schools.com/jsref/jsref_todatestring.asp
Mozilla Developer Network: link
Microsoft Developer Network: link
As you can see, all of them converge, its the week day, the month name, both with 3 characters, day of month and full year.
The specification does not define the output of the string:
The contents of the String are implementation-dependent, but are intended to represent the "date" portion of the Date in the current time zone in a convenient, human-readable form.
This might change in the future, but for now, each browser/environment can produce a different output.

Is it possible to implement a way to "guess" this date format based on the information in the array?

In JavaScript Language ,
I have an array ... maybe it look like this
var all_date = new Array( "11/12/2009", "31/12/2010", "29/12/2011", "17/09/2011" );
Is it possible to implement a way to "guess" this date format based on the information in the array and perhaps suggest to user which date format is most likely? Such as ... DD/MM/YYYY
Well of course, if the data happens to conveniently contain day values greater than 12 and have four-digit years (as the data you've quoted does), you're not guessing, you can be certain you've got the right format.
But if it happens that all of the day values in the data are 12 or lower, it's impossible to be certain whether the data is in U.S. MM/DD/YYYY format or the more common DD/MM/YYYY.
So no, you can't reliably infer the format in the general case. The source of the data should provide the format information (in documentation, etc.), and ideally use a less ambiguous format such as YYYY/MM/DD.
Well, to a certain degree, yes, you can. One obvious method is by using regular expressions. Suppose you have a date, like 2020-10-31, you can test it against a RegExp, extract tokens(year, month and day of month) and once tokens are identified, you can map them to their corresponding format tokens(YYYY, MM and DD).
Now consider the RegExp, /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/; put in simple words, it matches string of the form (4-digit year)-(month, maybe)-(day of month, maybe); parentheses imply capture groups. Capture groups here, will essentially pull out the tokens for you(year, month and day of month parts). Try out the following snippet,
console.log('2020-10-31'.match(/^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|3[0-1])$/));
Once the tokens have been identified, it's easy to construct the format string, YYYY-MM-DD.
Be warned though, if the date is ambiguous, you can't accurately determine token semantics. Consider the date 01/01/2020, it could be any of DD/MM/YYYY or MM/DD/YYYY. Nonetheless, the method works quite well for standard date-time formats(ISO 8601 and RFC 2822).
Detailed references :-
Regular expressions
Here is a snippet from moment.js source code which does what you asked, but only for ISO 8601 compliant dates
Here is a package I wrote, which does the same thing for other formats as well, accounting for the ambiguities.

Categories