globalizejs / globalize Goto Github PK
View Code? Open in Web Editor NEWA JavaScript library for internationalization and localization that leverages the official Unicode CLDR JSON data
Home Page: https://globalizejs.com
License: MIT License
A JavaScript library for internationalization and localization that leverages the official Unicode CLDR JSON data
Home Page: https://globalizejs.com
License: MIT License
parsing using the Hijri calendar fails in "d" mode.
ex "04/11/90" (Thu Dec 31 1970) => Sat Feb 17 2553
// Fredrik Blomqvist
This results in a lot of duplicate definitions. It would seem more logical to base extensions on the hierarchy of languages.
For example, both jquery.glob.fr-FR.js (French/France) and jquery.glob.fr-CA.js (French/Canada) should extend jquery.glob.fr.js (French). Currently, the same properties are repeated in the three files.
Hello,
My team is developing an e-commerce framework in ASP.Net MVC. Recently we upgraded it to MVC 3, and I have spent a large part of the day testing the new jquery.validate/unobtrusive javascript goodness.
All in all, it went pretty smooth, but our framework is intended to be multi-language oriented (or at least french oriented), and the need for a localization library came quickly. Previously we were using the Ajax.GlobalizationScript and the MicrosoftAjaxMvcValidation libraries, which were a little bit limited, but worked well.
I was excited by the possibility to use jquery.validate and all its neat features, but... it's proving very difficult to use it on an international website. Of course I expected jquery.global to come to the rescue, but it's not very easy. For example : validation of comma separated decimal numbers (which are default in french). A lot of forums like StackOverflow are giving this little trick :
jQuery.validator.methods.number = function (value, element) {
return !isNaN(jQuery.global.parseFloat(value));
}
It works quite well, but actually you need to do that kind of "bridging" with all methods that parse possible decimal numbers (like range validation).
I'm perfectly aware that this concerns jquery.validation as much as jquery.global (if not more), but I think it's really REALLY time for those two excellent official plugins to hold their hands and work together. Even more goodness will come from it.
In the meantime, keep up the good work!
Hello,
Following a link on a Scott Guthrie blog post (but I have also seen others) I browsed the old nje (https://github.com/nje/jquery-glob) github repository. Believe it or not but it took me TWO HOURS to notice something was wrong (the fact that all files had not been commited since july 2010 helped).
I know you have probably no power on those sites and blogs, but can't you do some redirection, or just shut down the old repository, or at least put a big "OBSOLETE, GO HERE" message on the homepage?
parsing "d" dates using the UmAlQura calendar returns null dates.
// Fredrik Blomqvist
trying to parse any of the date-formats using the ja-JP Japanese calendar seem to fail with a 100 year offset. Well, all but the last "1955" example.
// Fredrik Blomqvist
Globalize.parseInt should truncate negative numbers not round them, just like JavaScript global object parseInt
Why not just make the globalization files into JSON files? This way it is independent of any namespace and it would reduce the redundancy of code in each file (defining "cultures", etc). Plus, this makes it more portable in case some other plugin needs to tap into a culture definition. The exception to this would be, of course, if a culture definition contained a function, but I don't see that anywhere.
Of course this would mean the inclusion of an additional function which handles loaded culture definition files, but it seems more intuitive that way. The only potential downside to loading files in this manor is that you can't simply have a list of script includes for individual culture definitions, but if they are going to be static anyways, it would be very easy for the developer to compile the needed definitions into a single file that extends the cultures object itself.
The 'englishName' property for the en-US culture is 'English'. This should be English (United States), just as en-GB is English (United Kingdom)
Currently, when using Globalize, the following warnings are displayed in the error log:
variable deep redeclares argument
(in private utility functions)
function getPart does not always return a value
assignment to undeclared variable culture
in:
Globalize.format = function( value, format, cultureSelector ) {
culture = this.findClosestCulture( cultureSelector );
Although these are not serious, it would be better to have them removed, partly to avoid questions "why these warnings?", partly to make it a little easier to deal with other warnings (so that when you see that there are warnings, you would knoiw that there is something else than these routine warnings).
I'm not sure I see the point of item 1. Why declare something as a parameter if you start by setting its value to false? The code accesses the parameters in other ways, so I don't see why it has a dummy parameter list at all and why it uses the name "deep".
Item 2 is about a function that ends with a switch statement without a default branch. I guess putting just "return undefined" after the switch statement would silence the warning, though it might be preceded by raising an error (as we don't expect to come there).
Item 3 is just about forgetting to declare "var culture" in the function, right?
Globalize.parseFloat("4,0",10,"en") yields 40, which is unacceptable. It should either work the same way as the standard parseFloat, parsing a number at the start of its first parameter (yielding 4) or parse the entire attribute as a number, recognizing that it does not fit into the number patterns of the locale (yielding NaN). The latter is preferable, as it would help in detecting data errors (like input "4,0" when a number in the English locale is expected).
It is highly probable that input like 4,0 in English locale is data error. It is extremely improbable that the user really meant the number 40
Technically, parseFloat, upon encountering a group separator, should test that there is a correct number of digits after it, as defined by numberFormat.groupSizes.
Similar considerations apply to parseInt, of course.
The description of ”d” number formatting code as ”for decimal digits” sounds very odd. It seems that the format code ”d” really means using the non-localized JavaScript number format, just with left-padding the string with zeros to get a minimum width specified by number after the format character ”d”.
So Globalize.format( 123.45, "d" ) yields 123.45 (not 123 as currently in the documentation). Maybe the documentation is meant to use 123 as the first parameter, on the grounds that the ”d” format is really meant for integers only, isn’t it? Moreover, it should perhaps be emphasized that the result is not localized, e.g. Globalize.format( 1234, "d") yields 1234 independently of locale, not a localized presentation with a thousands separator (1,234 or 1 234 or something like that).
Trying to use the revamped jQuery Global, i.e. Globalization, in the most obvious way...
<script src="jquery/lib/globalize.cultures.js"></script> <script src="jquery/globinfo/Globalization.all.js"></script> <script>alert(Globalize.format(new Date(),"D","fi"))</script>I get the error message "Globalization is not defined". Apparently the reason is that Globalization.all.js uses the identifier "Globalization".
So there's presumably something not quite finished yet in the transition or there is something one should do (define "Globalization"?) before calling the methods, but what? (The documentation is silent about this.)
In Globalize.format() for dates, the formatting codes 'z', 'zz', 'zzz' currently use representations where the separator between hours and minutes is ':' (colon) and the minus sign is '-' (hyphen-minus, i.e. ASCII hyphen). These characters should be localized according to calendar[:'] and numberFormat['-'].
Demo code (the second part needs to be tested in an environment where the system's time zone is GMT minus something):
var d = new Date();
var p = document.getElementById('p');
Globalize.culture('bn');
p.innerHTML = Globalize.format(d,'F') +
'
' + Globalize.format(d,'zzz');
Globalize.culture('en');
Globalize.culture().numberFormat['-'] = '\u2212'; // Unicode MINUS SIGN
p.innerHTML += '
' +
Globalize.format(-42) + '
' +
Globalize.format(d,'zzz'); // should show MINUS SIGN (longer than ASCII hyphen)
The first line of output shows that in the 'bn' culture, the 'F' format uses a time denotation with "." (period) between hours and minutes, as well as between minutes and seconds. Yet the second line shows that 'zz' is implemented so that ':' (colon) is used.
When a specific culture is loaded, but not the generic language culture preferring the language should match that culture.
So when de-DE is available, but nothing else, findClosestCulture("de") should match "de-DE".
Globalize.preferCulture() was renamed to Globalize.culture(), but under the heading "Globalize.culture( name )", there are still three references to preferCulture in the examples.
In the NL culture, and other European cultures as well (except for the UK).
We use the 24 hour (HH) time notation instead of the 12 (h) time notation.
Without something like am/pm its unclear what part of the day it is.
// Expected
Globalize.parseInt( Globalize.format(-3.91, "c") ); // -3
Globalize.parseFloat( Globalize.format(-3.91, "c") ); // -3.91
// Actual
Globalize.parseInt( Globalize.format(-3.91, "c") ); // NaN
Globalize.parseFloat( Globalize.format(-3.91, "c") ); // NaN
The expected values are returned if the original value is positive rather than negative.
parseFloat doesn't crok any currency symbols, so in order to parse currencies correctly we need a seperate parseCurrency method. It needs to be able to handle anything output by format(123, "c")
I was looking into using this library and I wasn't sure where these date formatting tokens came from. Many libraries (date.js, django, etc...) use a PHP-like formatting for input an output. Sometimes the strftime format is used. For instance, the Django documentation explains how to get the framework to provide a js file with this in it:
formats['DATETIME_FORMAT'] = 'N j, Y, P';
formats['DATE_FORMAT'] = 'N j, Y';
formats['DECIMAL_SEPARATOR'] = '.';
formats['MONTH_DAY_FORMAT'] = 'F j';
formats['NUMBER_GROUPING'] = '3';
formats['TIME_FORMAT'] = 'P';
formats['FIRST_DAY_OF_WEEK'] = '0';
formats['TIME_INPUT_FORMATS'] = ['%H:%M:%S', '%H:%M'];
formats['THOUSAND_SEPARATOR'] = ',';
formats['DATE_INPUT_FORMATS'] = ['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y'];
formats['YEAR_MONTH_FORMAT'] = 'F Y';
formats['SHORT_DATE_FORMAT'] = 'm/d/Y';
formats['SHORT_DATETIME_FORMAT'] = 'm/d/Y P';
formats['DATETIME_INPUT_FORMATS'] = ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M', '%m/%d/%y'];
These values are pulled from the application settings. It would be really nice to be able to pass these settings directly into jquery.global to keep the server side and javascript in sync. The only issue is that I don't see the "j" option here. In jquery.global the "day of week without leading 0's" would be done with "d"
Are the formatting options used here taken from somewhere in particular? The date.js library allowed you to pull in an "extra" PHP compatible formatting lib. Would something like that be possible?
In the documentation, right before the heading "Number Formatting", there is the following code sample:
// switch to a non-standard calendar
Globalize.culture.calendar = Globalize.culture.calendars.SomeOtherCalendar;
// back to the standard calendar
Globalize.culture.calendar = Globalize.culture.calendars.standard;
That won't work, since Globalize.culture is a function and has no property called calendar. To fix this, add the parentheses () to make it a function call.
It might be a good idea to add the following to the documentation:
Called with an empty parameter list, Globalize.culture() returns the current culture.
the parseDate and parseNumber input boxes in the demo are currently non-functional.
Instead of calling
// Fredrik Blomqvist
Test 3: equal( Globalize.parseInt("($5.51)"), -5 );
Expected: -5
Result: 0
Test 4: equal( Globalize.parseFloat("($5.51)"), -5.51 );
Expected: -5.51
Result: NaN
I might have some time to look into this later, if nobody else gets to it.
EDIT: I see this in Chrome, too. Maybe it is cross-browser.
Should be possible to run unit tests headless, via command line. Can make use of QUnit's node-wrapper, even though that needs some love: https://github.com/jquery/qunit/blob/cli/test/suite.js
Maybe use node-qunit: https://github.com/kof/node-qunit
The description of ”d” number formatting code as ”for decimal digits” sounds very odd. It seems that the format code ”d” really means using the non-localized JavaScript number format, just with left-padding the string with zeros to get a minimum width specified by number after the format character ”d”.
So Globalize.format( 123.45, "d" ) yields 123.45 (not 123 as currently in the documentation). Maybe the documentation is meant to use 123 as the first parameter, on the grounds that the ”d” format is really meant for integers only, isn’t it? Moreover, it should perhaps be emphasized that the result is not localized, e.g. Globalize.format( 1234, "d") yields 1234 independently of locale, not a localized presentation with a thousands separator (1,234 or 1 234 or something like that).
GitHub's parser removes the id attributes, so need to put back the anchor elements for the readme navigation to work. Ignore if docs get moved to api.jquery.com
The Globalization plugin defines methods, both public and private, that are already part of jQuery:
Is there something specific in these implementations that prevents calling jQuery methods instead?
jquery-global.js, method formatDate(), about line 1240.
The variable "names" is missing the "var" keyword thus creating an accidental global.
We don't want two version of the plugin in the repository, but there should be a build to create a jQuery-independent version for releases.
When the string does not contain a recognizable number, Globalize.parseInt returns 0, as opposite to parseInt, which returns NaN. It is essential to return NaN, since otherwise the caller cannot distinguish between invalid data and input data representing the number zero.
The problem is in the function
truncate = function( value ) {
return value | 0;
};
which is currently used in two contexts: 1) to define Globalize.parseInt so that it truncates the return value of Globalize.parseFloat, and 2) in formatNumber when using the "d" format code.
Minimal fix: change the statement to
truncate = function( value ) {
return isNaN(value) ? NaN : value | 0 ;
}
(This relates to issue #41 at least in the sense that considering it, I noticed this discrepancy.)
The en-GB culture uses the H formatting code (24-hour times) for times in the definitions for codes like "t". Yet, it has no explicit setting for the calendar.AM and calendar.PM properties, which means defaulting them to the en (default) locale, which in turn effectively means using 12-hour times.
This means that there's no global way of requesting for, say, a format that consists of hours only, in the locale's hour notation. If the locale definitions were consistent, we could use
function hour(d) {
return Globalize.format(d, Globalize.culture().calendar.AM !== null ? 'h tt' : "''H" );
}
(That is, use 12-hour number followed by AM/PM designator if the locale uses 12-hour times, 24-hour number otherwise.)
jquery.glob.js:768: ERROR - Parse error. Trailing comma is not legal in an ECMA-262 object initializer
I don't see jquery.global.js and jquery-1.4.4.js any more listed on the page
https://github.com/jquery/jquery-global
or in the .zip package!
Number formatting of a currency is generally not cultural. It is an aspect of the data itself. Cultures do have one or more commonly used currencies, however the display of the currency needs to be tied to the data. For example, just because I am an American working with Yen in Japan, I don't expect my bank account to look like "¥1,000,000.00"... Yen should never be written with decimals, regardless of what your browser or application's culture is set to.
I'd suggest the creation of a separate object to encapsulate all currencies and reference that in the culture. For instance, remove the currency out of the number formatting section and add a commonCurrencies: ["USD"]
field for each culture. Then you could have a parseCurrency(value, radix, currency)
that accepts these objects.
Since I'm currently working on extending the python-money code, I could generate the javascript structure for you using ISO-4217 data pretty easily. Something like this:
[
{
symbol: "",
countries: [
"ALGERIA"
]
code: "DZD",
decimals: 2,
numeric: "012",
name: "Algerian Dinar",
},
...
{
symbol: "$",
countries: [
"AMERICAN SAMOA","BRITISH INDIAN OCEAN TERRITORY","ECUADOR","GUAM","MARSHALL ISLANDS","MICRONESIA","NORTHERN MARIANA ISLANDS","PALAU","PUERTO RICO","TIMOR-LESTE","TURKS AND CAICOS ISLANDS","UNITED STATES MINOR OUTLYING ISLANDS","VIRGIN ISLANDS (BRITISH)","VIRGIN ISLANDS (U.S.)"
]
code: "USD",
decimals: 2,
numeric: "840",
name: "US Dollar",
},
...
]
It might be that the common case is web-apps where the currency is consistent with the user's culture. I don't want to overly complicate the library. I do think that this kind of structure more accurately reflects the real world. Would anyone be interested in something like this?
Hi,
I need to store some messages in default culture (to use them when localized one are not stored in the specific culture). But Globalize.localize returns "undefined" if a message is placed in the default culture only.
It seems that this method contains mistake.
Globalize.localize = function( key, cultureSelector ) {
return (
this.findClosestCulture( cultureSelector ).messages[ key ]
||
this.cultures[ "default" ].messages[ "key" ]
);
};
For the specific culture messages are taken using key parameter that is passed to function, but for the default culture messages are taken using "key" string.
Could you please correct this if it is a mistake or explain why hard-coded "key" string is used for the default culture?
Need to get rid of globinfo/*.min.js and a build file to create those for releases.
There does not seem to be any option to specify that dates should be formatted as UTC, instead of in the local timezone.
parseInt and parseFloat both have 10 as a default for the radix argument, but when specifying a culture, the radix argument has to be provided again. There should be some internal argument shufflich to allow specifying the culture (string) without the radix (number).
Here's some pointers:
http://www.farsiweb.ir/wiki/Iranian_calendar
http://farhadi.ir/works/jalalijscalendar
Guess it should (at least) be added to the "fa-IR" and "*-AF" locales.
// Fredrik Blomqvist
parseDate calls parseExact which in turn calls getParseRegExp. The following is used to build part of the validation regex:
case 'dd': case 'd':
case 'MM': case 'M':
case 'yy': case 'y':
case 'HH': case 'H':
case 'hh': case 'h':
case 'mm': case 'm':
case 'ss': case 's':
add = "(\d\d?)";
break;
Shouldn't this be split between formats requiring a leading zero and those that don't? Currently this allows 2011-4-4 to be parsed with a yyyy-mm-dd format, which seems odd.
It doesn't seem like any one character date formats are valid right now unless they are contained in the calendar.patterns
object (lines 431-437):
if ( len === 1 ) {
pattern = patterns[ format ];
if ( !pattern ) {
throw "Invalid date format string \'" + format + "\'.";
}
format = pattern;
}
Seems like there should be some way at getting at single date properties, like month or hour.
Not sure where you got your definition of "culture" from, but in programming the de-facto standard term for managing I18n-ish data is "locale"/"locales". Why reinvent the wheel and make things confusing like this? "Culture" is so misleading. =S
There's some ordering/dependency issue in the testsuite, causing certain tests to pass by themselve, but fail when ran together with the full suite, but not always: http://bassistance.de/i/37028d.png http://bassistance.de/i/11367b.png
Trying to use Globalize.culture() with a parameter that is a valid code for country variant of a language, like "es-AO", seemingly works in the sense that the function returns a culture corresponding to the language generically, like "es":
alert(Globalize.culture("es-AO").name)
shows "es".
But using format() with the culture defaulted, like
alert(Globalize.format(new Date(),"D"));
fails to use the "es" culture and uses "en" settings instead. For comparison, the operation with an explicit culture parameter works (Spanish date presentation appears):
alert(Globalize.format(new Date(),"D","es-AO"));
Here's correct values:
平成 (year offset 1988)
昭和 (year offset 1925)
大正 (year offset 1911)
明治 (year offset 1867)
function expandYear( cal, year ) {
// expands 2-digit year into 4 digits.
//var now = new Date(), era = getEra( now );//this line should move into the if... block
if ( year < 100 ) {
var now = new Date(), era = getEra( now );
//....
}
return year;
}
$.format
formats Infinity
in a very peculiar way: "In.fin.ity"
. I haven't checked it in other cultures, but I suspect $.format(Infinity, 'n0', 'en-GB')
would yield "In,fin,ity"
.
Although I don't think a lot of people will have to deal with values as Inifinity
or -Inifinity
(which also yields "In.fin.ity"
), this is still a bug.
More erroneous behavior:
> $.format(-Infinity, 'n2')
"In.fin.ity,00"
What was the motivation for dropping the "invariant" culture? (commit 099e13a)
Even if not being set as the default culture, I think it would be useful to maintain symmetry with for example .NET that exposes it.
// Fredrik Blomqvist
In two places the built in parseFloat() function is called with an invalid second radix argument, parseInt() style.
// Fredrik Blomqvist
Hello,
I don't know which minifier you use but the minified version of the fr-FR settings is buggy (jquery.glob.fr-FR.min.js). It just won't load correctly, throwing an error in Firebug. The non-minified version is OK.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.