Javascript: data format, akin to Spring Property Editors - javascript

Is there any library already available for javascript data format / transformation?
Example: Date, Time, Numbers, etc., can be converted to text with predefined formats.
These formats are chiefly locale based. But some how the mechanism to convert value (data, date, time..) should be there, that accepts custom format too to translate into desired formatted text.
On the contrary, the same library should be capable of parsing the text to value, with the source format knowledge.
Some thing similar to Spring's Property Editors or Converter.
Quick Searches; http://numeraljs.com/ http://www.datejs.com/
I should have mentioned the fact that, I am using DOJO as our JS Widget Library and with it comes methods and classes to address formatting / parsing, bundled.
Now that we have DOJO in place, I will be putting the code in the abstract layer (wrapper) over the library to keep the solution Library-Agnostic.
Find the code below - for brevity only the snippet is mentioned, could have done JSFiddle (may be in a day or two).
// get the DOJO handle, either from global "dojo" variable or via AMD
// var dojo = require('dojo');
............
// for date
dojo.date.locale.format(new Date(), {selector: "date",datePattern:"dd/mm/yyyy"});
// output: 31/06/2013
// for number
dojo.number.format(9999999.99,{type: "decimal",pattern:"#,##,####.##"});
// output: 9,99,9999.99
............
NOTE: An important feature it addresses is that it understands locale and can do the formatting automatically w.r.t the locale configured. DOJO library staunchly follows Java style of data formatting. If you are a Java Geek, you would find the library and format semantics easy to follow.
Find the DOJO link in this respect ://dojotoolkit.org/reference-guide/1.7/quickstart/numbersDates.html (could not post the complete link as I do not have enough reputations, please prefix "http" to the link)
Still, I would like to welcome better solution if any, for the given context.
As part of libraries used, we are using jQuery, Underscore, Backbone and DOJO primarily , all across for specific purposes in the application.

I use Moment.js for all my JS date formatting and manipulations. http://momentjs.com/

Related

JS Static Checks to verify library isn't used

My application used moment in lots of places to apply a range of date-time formats.
To achieve consistency, I've switch to wrapping moment formatting inside new formatDate() and formatTime() convenience methods. Now dates and times will always be formatted in consistent methods. I've also been able to include some timezone-sensitive handling in the helpers.
But, in the future it will be all-too-easy to start letting instances of moment.format() into the code again, and allow a range of date-time formats.
Is there a static analysis tool (hopefully CI compliant) that checks that particular classes/methods are NOT used in code?
Obvs there would be an exclusion comment in the two instances where I legitimately used moment.

Using moment.js, how to display the current date format for the user?

Given a text field, I want to have a suitable placeholder. A typical placeholder will be something like: "mm/dd/yyyy".
However, I would like to use locale-aware dates using moment.js.
This means that I will be specifying "l" as the moment.js date format, howe do I determine the date format that moment.js will be using in this case?
The user will not understand what "l" means, so using this value in the placeholder text makes very little sense.
Specifically, I am hoping to be able to access something like moment's internal "defaultLongDateFormat". (Though that is merely a default - moment.js probably updates it or has some other mapping at runtime for locale-aware date formats - I would like to access that mapping.)
EDIT:
There are multiple downvotes (who aren't explaining why they're downvoting it).
I think this is because they arent' understanding the question, so here are some examples:
I want a function such that:
getFormat("l") -> "mm/dd/yyyy", or equivalent for the US locales.
getFormat("l") -> "dd/mm/yyyy", or equivalent, for the AU locales.
I do not want to format a given date, or to parse a given date - I merely want to determine it's user-friendly format given an arbitruary moment.js format, specifically, for 'l'.
I don't think it's exposed nicely, but if the browser has its language configured correctly you can do something like this:
var lang = navigator.languages ? navigator.languages : navigator.language;
moment().locale(lang).localeData()._longDateFormat['L']
Languages behave slightly differently depending on which browser you're using, so don't know how reliable this is.
Follow up to Adam R's answer:
Seems to have been exposed by now:
localeData.longDateFormat(dateFormat);
returns the full format of abbreviated date-time formats LT, L, LL and so on
(source: http://momentjs.com/docs/)
Get the currently used locale data by moment.localeData()

Knockout - Export html table with formatting

How can I export a table generated using Knockout that will maintain the formatting?
I was using this solution (How to export html table to excel using javascript), but it does not include formatting.
As I mentioned in my comment, excelbuilderjs.com might work out for you. There are a couple of distinct downsides - one in that you can't simply turn an HTML table into an excel spreadsheet with colors and etc. It does require setup. But, in the case of where I work, we have a fairly standard color scheme and set of formatters that has been translated into a standalone set of instructions that is then included everywhere we need to construct a spreadsheet.
Based on a few simple examples of Knockout, you could probably just use the same data source to loop through and assign to EB - then just assign number formatting and date formatting as you would for an actual excel spreadsheet (i.e. $#,##0.00 for basic currency, m/d/yyyy for a basic date).
Side note - apparently some of my documentation didn't make it up.
http://excelbuilderjs.com/cookbook/formatting.html is where you can get some basic info on formatting.

localizing strings in javascript

We need to be able to localize strings in javascript - thinking for things like the app_offline.htm file etc.
jquery globalize is hectic and seems like total overkill. Is there a simple jquery plugin or anything really that will allow us to localize js strings?
At the risk of over simplifying:
var globals = {
en-US: {
color:'color',
cell:'cell phone'
},
en-GB: {
color: 'colour',
cell: 'mobile phone'
}
};
To use:
text = globals[lang].color;
where lang = 'en-US' etc
You can either generate that structure on the server and use resource files etc there, or just keep this object literal in a global.js or similar.
The Globalize.js library, previously known as jquery-global or jQuery Globalize, is relatively small, but if you only need string localization (and not date and number localization as well), then it does not offer much more than a general setup: locale (culture) object containing the property messages. It is initialized to an empty object, and you are supposed to add properties to it, corresponding to your strings to be localized. And it has the simple method Globalize.localize() that selects a localized string for a key
To implement simple string localization, you do not necessarily need any library or plugin. You could just code some simple approach like that of Globalize.js; the general code is fairly simple, much less work than defining the actual localizations for each string. On the other hand, if you have localization needs, you might just as well use Globalize.js, preparing for other kinds of localization in the future.

Localize dates on a browser?

Let's say I have a date that I can represent in a culture-invariant format (ISO 8601).
I'll pick July 6, 2009, 3:54 pm UTC time in Paris, a.k.a. 5:54 pm local time in Paris observing daylight savings.
2009-07-06T15:54:12.000+02:00
OK... is there any hidden gem of markup that will tell the browser to convert that string into a localized version of it?
The closest solution is using Javascript's Date.prototype.toLocaleString(). It certainly does a good job, but it can be slow to iterate over a lot of dates, and it relies on Javascript.
Is there any HTML, CSS, XSLT, or otherwise semantic markup that a browser will recognize and automatically render the correct localized string?
Edit:
The method I am currently using is replacing the text of an HTML element with a localized string:
Starting with:
<span class="date">2009/07/06 15:54:12 GMT</span>
Using Javascript (with jQuery):
var dates = $("span.date", context);
// use for loop instead of .each() for speed
for(var i=0,len=dates.length; i < len; i++) {
// parse the date
var d = new Date(dates.eq(i).text());
// set the text to the localized string
dates.eq(i).text(d.toLocaleString());
}
From a practical point of view, it makes the text "flash" to the new value when the Javascript runs, and I don't like it.
From a principles point of view, I don't get why we need to do this - the browser should be able to localize standard things like currency, dates, numbers, as long as we mark it up as such.
A follow up question: Why do browsers/the Web not have such a simple feature - take a standard data item, and format it according to the client's settings?
I use toLocaleString() on my site, and I've never had a problem with the speed of it. How are you getting the server date into the Date object? Parsing?
I add a comment node right before I display the date as the server sees it. Inside the comment node is the date/time of that post as the number of milliseconds since epoch. In Rails, for example:
<!--<%= post.created_at.to_i * 1000 %>-->
If they have JS enabled, I use jQuery to grab those nodes, get the value of the comment, then:
var date = new Date();
date.setTime(msFromEpoch);
// output date.toLocaleString()
If they don't have JS enabled, they can feel free to do the conversion in their head.
If you're trying to parse the ISO time, that may be the cause of your slowness. Also, how many dates are we talking?
Unfortunately, there is not.
HTML & CSS are strictly used for presentation, as such, there is no "smarts" built in to change the way things are displayed.
Your best bet would be to use a server side language (like .NET, Python, etc.) to emit the dates into the HTML in the format you want them shown to your user.
It is not possible to do this with HTML, it has no smart tags that can make any kind of decisions like this. It is strictly presentational. I do wonder, though, if HTML5 perhaps has a tag for something like this...
Anyways, the way I see it, you have 3 options:
Stick to the Javascript way. There's questions with more details on it on this website, such as How do I display a date/time in the user’s locale format and time offset? and How can I determine a web user’s time zone?
Try to use geolocation. That is, your server side script fires off a request to one of the many geolocator services out there on the user's first page visit to try and guess where the user is. The downside of this is that it will be wrong about 10% of the time, so it's not that much better than the market share Javascript is going to get you.... (all in all, then, not a very good method...)
Ask the user! You will see that most websites that want to display a tailored experience for you will ask you this sort of thing because it's just not possible to know. As a neat fallback, you could wrap the question around <noscript> tags so you only ask those with Javascript disabled while offering the Javascript experience to those that have it.
Dojo has some pretty good localizations for dates and currencies. Using this method also allows you to pick different formats (e.g.: short date vs long date) and force locales.
The language and the user's locale should be sent on the HTTP header. You can use those to create the correct date format server-side to be displayed to the user. However, this is often undesirable because many users completely ignore their locale settings in their OS and/or browser. So, you may be feeding USA style timestamps to New Zealanders.
I liked the trick posted in the comment above, but it sounds like a QA headache, since you could be dealing with a large number of clients that implement timestamps in very different ways.
The most effective solution I have seen, is to simple provide a panel to allow your users to choose what time format they like. Some users even ****gasp**** like ISO formats. Then you do the time format conversion server side. If your application language does not have good locale to timezone formatting mapping, check your database. Many databases provide locale-based customized timezone formatting as well.
Because this anwser still popups in google I share that this is now possible to do by using a readonly datetime-local input (see below) and you can then style the input the way you want:
<input type="datetime-local" value="2018-06-12T19:30" readonly />
For more information see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local

Categories

Resources