I have rendered the normal text with jquery date rule. The date rule working fine in chrome but not working in the Firefox and IE . please see my code block.
<form id="myform">
<input id="datepick" type="text" name ="datepick"/>
<input type="submit" id="ValidateDate" />
</form>
$("#myform").validate({
rules: {
datepick:{
date:"MM/dd/yyyy"
}
},
messages: {
datepick:{
date:"Give MM/dd/yyyy format"
}
}
});
$('#datepick').keyup(function () {
$("#ValidateDate").submit();
});
</script>
when i type 12/3err/3001 it throws error in all browser
when i type 12/234/2333 it throws error chrome not in firefox and IE.
Additionally i want to share one information.
http://jqueryvalidation.org/date-method/
In the above link jQuery validation is not working properly in Mozilla , IE browser even for a normal textbox.
please type the 22/233/2222 value in the above jquery link sample then you can find the below output variation
In chrome :
In Firefox:
Please help me to resolve this.....
Thanks,
Gobalakrishnan
The documentation you've linked to says this:
This method should not be used, since it relies on the new Date constructor, which behaves very differently across browsers and locales. Use dateISO instead or one of the locale specific methods (in localizations/ and additional-methods.js).
My emphasis.
This issue is due to the date parsing behavior difference between the browsers. You can see the below.
Chrome
new Date("92/12/2015")
- Invalid Date
FireFox
new Date("92/12/2015")
- Date {Sun Jun 07 1998 00:00:00 GMT+0530 (India Standard Time)}
The date rule will only check for format based on inputted date value and hence the validation succeeded in FF.
So as #SomekidwithHTML proposed you can use the dateIso which will check the date against ISO date standards or implement your our custom validation as per your need.
http://jqueryvalidation.org/jQuery.validator.addMethod/
Related
This question already has answers here:
Detecting an "invalid date" Date instance in JavaScript
(52 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 5 years ago.
Chrome returns valid date for string "FY 2000" instead of invalid date while others browsers are correctly returning "invalid date"
Fiddle link: https://jsfiddle.net/Lddr79ek/
Code:
function isDate(value)
{
return new Date(value).toString()!= "Invalid Date");
}
is this an issue in chrome browser ?
Edit
The problem is the reported behavior breaks our product only in chrome browser. I checked other answers in SO but they are also not working in chrome.
I don't think it is a bug. When you call Date constructor with a string as an argument, that string parses via Date.parse.
And MDN says:
Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.
It also says:
However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in NaN, depending on the browser and values provided, e.g.:
It looks like current V8 (Chrome) parse implementation tries to guess, what was passed.
FYI:
Related issue on crbug: #126448
V8 Date.parse implementation: dateparser-inl.h
Chrome is parsing only numbers in input string.
Example:
new Date('AS 2017') //Year part is parsed.
Sun Jan 01 2017 00:00:00 GMT+0300
new Date('XCNCNNC 2017') //Year part is parsed.
Sun Jan 01 2017 00:00:00 GMT+0300
new Date('FY2017') //without space. Year is not parsed.
Invalid Date
I am using the following code to convert a server-side date-time to local time using moment.js.
moment(moment('Wed, 23 Apr 2014 09:54:51 +0000').format('lll')).fromNow()
But I am getting:
Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
It seems I cannot get rid of it! How can I fix it?
To get rid of the warning, you need to either:
Pass in an ISO formatted version of your date string:
moment('2014-04-23T09:54:51');
Pass in the string you have now, but tell Moment what format the string is in:
moment('Wed, 23 Apr 2014 09:54:51 +0000', 'ddd, DD MMM YYYY HH:mm:ss ZZ');
Convert your string to a JavaScript Date object and then pass that into Moment:
moment(new Date('Wed, 23 Apr 2014 09:54:51 +0000'));
The last option is a built-in fallback that Moment supports for now, with the deprecated console warning. They say they won't support this fallback in future releases. They explain that using new Date('my date') is too unpredictable.
As an alternative, you can suppress showing the deprecation warning by setting moment.suppressDeprecationWarnings = true;
The date construction in moment internally uses the new Date() in the javascript. The new Date() construction recognizes the date string in either RFC2822 or ISO formats in all browsers. When constructing a moment object with date not in these formats, the deprecation warning is thrown.
Though the deprecation warnings are thrown, for some formats, the moment object will be successfully constructed in Chrome, but not in Firefox or Safari. Due to this, processing the date in Chrome may give results as expected(not all the time) and throws Invalid Date in others.
Consider, 02.02.2018,
Chrome - moment("02.02.2018")._d -> Fri Feb 02 2018 00:00:00 GMT+0530 (India Standard Time)
Firefox - moment("02.02.2018")._d -> Invalid Date
Safari - moment("02.02.2018")._d -> Invalid Date
So the moment.js is used at your own risk in case the recommended/standard formats are not used.
To suppress the deprecation warnings,
As suggested by #Joe Wilson in previous answer, give the date format on moment construction.
Example : moment("02.05.2018", "DD.MM.YYYY").format("DD MM YYYY");
Give the date in ISO or RFC2822 format.
Example : moment("2018-02-01T18:30:00.000Z") - ISO Format
moment("Thu, 01 Feb 2018 18:30:00 GMT") - RFC2822 Format - Format in Github
As suggested by #niutech in previous answer, set
moment.suppressDeprecationWarnings = true;
I suggest to overwrite the input fallback in moment.
moment.createFromInputFallback=function (config){
config._d = new Date(config._i);
}
As (3) will suppress all the warnings, (4) will suppress only the date construction fallback. Using (4), you will get Invalid Date as the internal new Date() is used and other deprecations can be seen in console, so moment can be upgraded or the deprecated methods can be replaced in the application.
If your date is passed to you from an API as string(like my issue), you can use a filter to convert the string to a date for moment. This will take care of the moment construction warning.
$scope.apiDate = 10/29/2017 18:28:03";
angular.module('myApp').filter('stringToDate', function() {
return function(value) {
return Date.parse(value);
};
});
Add it to the view:
{{apiDate | stringToDate | amDateFormat:'ddd, MMM DD'}}
In my case I was trying to generate a date time to include in my form data. But the format of the string I had access to looked like "10-Sep-2020 10:10" so when trying to use moment like
myDate = '10-Sep-2020 10:10';
moment(myDate).format('YYYY-MM-DD HH:mm:ss');
I got the deprecation warning. There is no problem using a string to create the date but you just have to let moment know what it is you are passing in. As in explicitly state the format it is about to receive, for example
moment(myDate, 'DD-MMM-YYYY HH:mm').format('YYYY-MM-DD HH:mm:ss');
result: 2020-09-10 10:10:00
That's it, the warning goes away, moment is happy and you have a date time format ready for persistence.
As indicated in the above answers. Providing the date format should work.
Why would I be getting the deprecation message with the following line of code. I thought the String + format was suppose to remedy the issue. moment.tz('2015:08:20 14:33:20', 'YYYY:MM:DD HH:mm:ss', 'America/New_York'). Also, please not I do not have control over the date format being provide. I know I can convert it myself to 'YYYY-MM-DDTHH:mm:ss' then moment does not show the deprecation message. However, according to the documentation, the line of code should work. Here is the deprecation message I am seeing.
"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. Please refer to
http://momentjs.com/guides/#/warnings/js-date/ for more info."
Moment’s usage is so widespread that it’s impossible to deprecate the current version over time. Check out this post on alternative options Migrating away from moment.js
I am fetching a date object from an API. Here's the format returned from the API:
"2016-04-05 13:39:46.612"
Chrome seems to interpret this and display it correctly, but in Firefox, Safari, and IE, I get either null or invalid date.
Chrome results:
console.log(purchaseDate)
>> Tue Apr 05 2016 13:39:46 GMT-0500 (CDT)
This HTML in Angular view: {{$scope.purchaseDate | date:'MMM d, y h:mm a'}}
outputs: Apr 5, 2016 1:39 PM
Firefox results (similar for Safari and IE):
console.log(purchaseDate)
>> Invalid Date
This HTML in Angular view: {{$scope.purchaseDate | date:'MMM d, y h:mm a'}}
outputs: null
I've tried formatting the date using moment.js before sending it to the browser (as suggested in answers to similar questions), but the results aren't much better:
Chrome results:
console.log(moment(purchaseDate).format())
>> 2016-04-05T13:39:46-05:00
Firefox results (similar for Safari and IE):
console.log(moment(purchaseDate).format())
>> Invalid Date
Any ideas? I'd like to use moment.js to get the parsing consistent, since I'm already using it elsewhere in my code.
If you're going to use moment with angular, you should also use angular-moment.
When loading your value, create a moment object instead of a Date object.
var purchaseDate = moment("2016-04-05 13:39:46.612");
This particular format is already recognized by moment.js, so you don't need to provide a format string when parsing. Though do be aware that it will be interpreted as local time. If you wanted it in UTC instead, then:
var purchaseDate = moment.utc("2016-04-05 13:39:46.612");
Either way, you can then use angular-moment to format it:
{{$scope.purchaseDate | amDateFormat:'MMM D, Y h:mm a'}}
Angular-moment also provide lots of other filters you can use if you like. Check out their docs.
I think I had a similar issue and for me the best solution was to use momentjs library to parse the date string:
bower install --save moment
and then for example:
$scope.purchaseDate = moment("2016-04-05 13:39:46.612", "YYYY-MM-DD HH:mm:ss.SSS").toDate();
see parsing format here: http://momentjs.com/docs/#/parsing/string-format/
in the HTML page for example:
{{purchaseDate | date:'medium'}}
beware that momentjs takes care of your local timezone and will the date accordingly change
I hope it helps.
I'm trying to do time calculation based on user input. Before firing the calculation, I'm using momentjs to validate that the user time input. It seems to be acting strangely. For example, here is undefined input in browser console:
>moment(undefined).isValid()
>true
How do I use momentjs to validate user input?
Edit:
It seems that in strict mode you can validate everything else but dates with timezone abbreviations (EEST):
Tue May 05 2015 12:00:00 GMT+0300 (EEST)
The z parameter used for abbreviation is deprecated due to browser incompatibility: https://github.com/moment/moment/issues/162
If you restrict the pattern of the input date - you must use something like this:
checksDate = moment(date, ['DD-MMMM-YYYY', 'DD.MM.YYYY', 'MM/DD/YYYY', 'YYYY-MM-DD'], true);
Where this array:
['DD-MMMM-YYYY', 'DD.MM.YYYY', 'MM/DD/YYYY', 'YYYY-MM-DD']
is yours patterns.
The Third parameter in my moment statement define that moment.js must use strict mode. That means you can't use "." instead "-" in ISO format: "1990-09-01", for example.
In Docs you can see this phrase:
Moment's parser is very forgiving, and this can lead to undesired
behavior. As of version 2.3.0, you may specify a boolean for the last
argument to make Moment use strict parsing. Strict parsing requires
that the format and input match exactly.
In browser's console:
moment(undefined).isValid()
true
moment(undefined, [], true).isValid()
false
But its strong recommended to use pattern as i used in my example above.
Because without it moment.js can do mistake for this dates:
"01.11.2000" and "11.01.2000" - it can be similar dates, then you use arbitrary user input.
read more:
moment.js Docs about validation
I hope, it's clear.
I am working on a project where I have to deal a lot with Date and Time. Server side technology is ASP.Net and at client side I am using jQuery and jQuery Week Calendar(a jQuery plugin).
So here is the problem described, I am receiving Data Time from server something like this 2012-11-13T04:45:00.00 in GMT format.
Now at client side, I want this Date Time to be converted to Locale Date Time Format, like whatever is could be IST, EST, PKT, etc.
To achieve this, I am using JavaScript method toLocaleString(). This only works fine in Chrome, in other browser it works inconsistently.
Here are its outputs in different browsers:
Google Chrome(Works fine):
Call:
new Date ("2012-11-13T04:45:00.00").toLocaleString();
Output:
Tue Nov 13 2012 10:15:00 GMT+0530 (India Standard Time)
Mozilla Firefox:
Call:
new Date ("2012-11-13T04:45:00.00").toLocaleString();
Output:
Tuesday, November 13, 2012 4:45:00 AM
Safari:
Call:
new Date ("2012-11-13T04:45:00.00").toLocaleString();
Output:
Invalid Date
Internet Explorer:
Call:
new Date ("2012-11-13T04:45:00.00").toLocaleString();
Output:
Tuesday, November 13, 2012 4:45:00 AM
For now these are the browsers where I tested.
Here is the Question:
I need a way to convert Data Time(having format like this 2012-11-13T04:45:00.00) To Locale Date and Time, no matter which browser client is using.
The short answer is no. toLocaleString can be implemented however the developers wish. What your question implies is that Chrome outputs the string you want.
If you would like to output that format consistently you'll need to use a separate library - like DateJS.
To do this with DateJS will need some standard format specifiers available in core.js and some that are only available in extras.js. The documentation has a list of all the format specifiers.
The string you want is:
Tue Nov 13 2012 10:15:00 GMT+0530 (India Standard Time)
So to get this from DateJS you'll need:
"D M d Y H:i:s \G\M\TO (e)"
The syntax for DateJS is:
new Date ("2012-11-13T04:45:00.00").format("D M d Y H:i:s \G\M\TO (e)");
Instead of using toLocaleString() which is outdated and implemented incorrectly for all web browsers, I strongly suggest using Globalize for date & time formatting.
Then to format date on the client side, all you have to do is to assign valid culture and simply call the format function:
Globalize.culture(theCulture);
Globalize.format( new Date(2012, 1, 20), 'd' ); // short date format
Globalize.format( new Date(2012, 1, 20), 'D' ); // long date format
Pretty simple, isn't it? Well, you'll have to also integrate it with your ASP.Net application, which complicates things a bit. First, you will need to reference the globalize.js the regular way:
<script type="text/javascript" src="path_to/globalize.js"></script>
Then it is best to include the right culture definition, that is the one you will need to use when formatting:
<script type="text/javscript" src="path_to/cultures/globalize.culture.<% = CultureInfo.CurrentCulture.ToString() %>.js"></script>
Finally you will need to set theCulture variable before you use it:
<script type="text/javscript">
var theCulture = <% = CultureInfo.CurrentCulture.ToString() %>
</script>
Of course the more elegant way to do it, would be to create a property or the method in the code-behind that will write down the appropriate scripts for you and then reference just the method, say:
public string IntegrateGlobalize(string pathToLibrary)
{
var sb = new StringBuilder();
sb.Append("<script type=\"text/javascript\" src=\"");
sb.Append(pathToLibrary);
sb.AppendLine("/globalize.js\"></script>");
sb.Append("<script type=\"text/javascript\" src=\"");
sb.Append(pathToLibrary);
sb.AppendLine("/cultures/globalize.culture.");
sb.Append(CultureInfo.CurrentCulture);
sb.AppendLine(\"></script>");
sb.Append("<script type=\"text/javascript\">");
sb.Append("var theCulture = ");
sb.Append(CultureInfo.CurrentCulture);
sb.AppendLine(";</script>");
return sb.ToString();
}
Then all you have to do, is to reference this method in the (master?) page head:
<head>
<% = IntegrateGlobalize("path_to_globalize") %>
...
</head>
Some issues
If you want to do it 100% correctly, you will need to enhance the Globalize culture generator to include 'g' format switch and then use this exact switch on the client side to format date:
Globalize.format( new Date(2012, 1, 20), 'g' ); // default date format
Why is that? Because 'g' is a default date format. This is what you'll get when you simply call DateTime's ToString() method without parameters (which will imply CultureInfo.CurrentCulture as the only parameter...). The default format is best, it will be either short or long, or any other, but the most commonly used by people using this culture.
I said that toLocaleString() is wrong for all web browsers. Why is that? That's because it will use web browsers settings and not the server-side detected culture. That means, that you might have mixed cultures in the same web page. That may happen if some of your dates are formatted on the server side and some other on the client side. That's why we needed to pass (detected) culture from the server side.
BTW. If you decide to include the regional preferences dialog to your web application, the mismatch would be even more visible, as toLocaleString() won't follow user settings...
To convert a time to a locale-specific string on the server, you can use the method DateTime.ToLongDateString. On that page, see the note about the "current culture object" (on the server) of class DateTimeFormatInfo. Make sure that's set correctly.
The root cause of this issue was never addressed by any of the answers. The OP said:
I am receiving Data Time from server something like this 2012-11-13T04:45:00.00 in GMT format.
GMT is not a format. This string is in ISO 8601 extended format, without any time zone specified. The ISO 8601 spec says that without a qualifier, this is intended to represent local time. To specify GMT, you would append a Z to the end, or you could append an offset such as +00:00.
The problem is, ECMAScript (v1 - v5.1) did not honor this provision in the spec. It actually said that should be interpreted as UTC instead of local time. Some browsers honored the ISO spec, some honored the ECMA spec. This has been corrected for version 6, and most browsers have complied.
So - if you intend to transmit UTC/GMT based timestamps, then on the server side, you should always send a Z so there is no ambiguity.
Still, even if the value is correctly interpreted, there's no guarantee that the strings will be formatted the same across browsers. For that, you do indeed need a library. I recommend moment.js, but there are others.