Localization and Time Format - javascript

We know that different locales use different date and number formats, but what about time formats? There are certainly fewer ways to format time values than date values.
I have a field in a web application that accepts a time value as free text, hour and minute only. Suppose that the field allows only one of the following formats for all locales.
23:59
2359
12:59p
p12:59
Note that "p" and ":" are customizable for each locale.
Would this be too much restriction for a localizable application supporting non-English locales? I'm asking since there's no built-in parser for time values in JavaScript and it seems that most projects build their own mini parser.

Maybe what you are looking for is JQuery Time Picker. I don't think any of these plugins support JQuery Regional scripts, but at least it should be easier to create your own localized settings instead building a parser...
If you still want to build a parser, go for it although trying to support all possible combination (like "6:40", "06:40", "6:40 P.M.") would be at least problematic. As Stefan mentioned, it is easier to do just some kind of drop-down boxes (personally I hate them as they require clicking). Otherwise you may create to text fields: one for hour part and the second one for minutes and add drop-down for selecting AM/PM conditionally (that is if preferred format for this locale is 12 hours).
What about time zones? I'd recommend that the user time zone would be in use, but the time would be then converted to UTC and stored as such internally...

Related

MomentJS: Display formatted range between two arbitrary dates

I have two arbitrary dates that I would like to compare using MomentJS. By "arbitrary," I mean that neither of them are now (i.e. moment()).
I would like to display both of these dates as a nicely-formatted string based on the difference between them. For example, if the difference between them is just a few hours, I'd rather display something like "5 am to 8am", rather than "1/1/2018 5:00am to 1/1/2018 8:00am".
Put more succinctly, I'm trying to see if moment can determine which fields are equivalent, and based on this, format the time range as a string without any redundant information.
Is there a way to do this using standard functions in MomentJS?
Here's what I understand so far:
The functions such as toNow(), fromNow(), to(), and from() all provide relative time ranges, but these are in reference to now. What I'm looking for is this same interface, but without referencing now.
I believe that my options are either to:
Use one of the aforementioned functions to compare the two dates, drop the suffix, and display something like "1/1/2018 5:00am + 3 hours", OR
Use a duration to compare the dates, and add custom code to determine equivalent quantities, and set the format accordingly. E.g. if years, months, weeks, and days are equivalent, format each timestamp as "h:mm:ss a".
The output of the second option would be much more desirable. Essentially, I'm trying to implement this option using MomentJS and as little custom code as possible.
It looks like this is handled externally by a plugin called Twix.

Angular app and internationalization and localization

we have an existing silverlight app which runs in browser + on hardware.
we want to rewrite this app using angular js and html5.
one of the key requirements with new system is support of internationalization and localization. and target countries are usa, brazil, italy for now.
Am new to this area and have lot of basic questions.
does existing database needs to be redesigned to support same ? i mean to identify columns (product_name/customer_name etc) that needs to have locale specific data and then store data for each locale and modify sprocs and webapi to accept language parameter and then get content based on that. ?
I believe we need to user nvarchar for such columns.
what will happen to currency and date time columns in db ? say there is quantity column then what should be data type of this column in db ? if current locale is Portuguese then will qty stored in Portuguese number.
what is the best practices for storing and retrieving currency column
based on locale.
what is the best practices for storing and retrieving date column
based on locale.
how to handle string checks, numeric checks in webapi methods ?
how to do comparison and checks in javascript for string,number,datetime
please share link to some good pointers which could help.
so in short right from javascript to .net webapi to database (sql) how should we take care of locale dependent logic and fields
thanks.
A lot of questions, let's see if I can answer those.
If your existing application is properly internationalized, I don't think there is any need to modify the database. Just make sure it is able to handle international characters (NCHAR, NVARCHAR, NTEXT in MS SQL, valid character encodings in others).
As for DB design, it is good to keep things locale-independent as long as you can. For instance it is better to store keys in the database and resolve them at runtime. However, if your data is dynamic (i.e. you have product names and their descriptions that changes often), the only way to go is to have translation table and look the data up using valid locale. It's quite complex in relational world (i.e. joins), but it could be done.
2,3. All the numeric columns should be kept locale-independent and formatted on the UI side. The more problematic would be prices and sales orders - you would need an additional column to store the currency code (i.e. 12.34 | USD). On the UI side you would need to pass the code to the Angular currency filter. The only gotcha here is, Angular does not support easy locale context switching, so you would need to use a hacky library like Angular Dynamic Locale to load the formats for you.
Similar. Keep it locale-independent. DB built-in types should automatically handle that for you and give you nice DateTime/DateTimeOffset (in a .Net world) back. The only gotcha would be the time zone - it may make sense to use DATETIMEOFFSET MS SQL type, as others does not store time zone.
There is an alternative way to store date and times in the database - you may decide to store it as a number of milliseconds since January 1, 1970 UTC - as BIGINT type. Especially if you are going to read this directly to JS, you will be able to easily re-create JS Date object (should you need this for calculations or something) in a valid time zone (it works the other way round as well). All you have to do to format date is to use this number (not date, that is AFAIR) and Angular's date filter with UTC as a parameter.
I don't think I understand what you're asking exactly. I guess the question is about validation of user input, rather than API. Well, beware of using Regular Expressions, because JavaScript doesn't handle Unicode well (at least in this area). You'd need to ask more precise question.
Assuming that you have Number and Date objects (i.e. typeof o == 'number') it is straightforward (as in obj1 === obj2).
As far as strings are concerned... Well, str1 === str2 will give you valid answer if you want to be exact. If you want to sort them, modern web browsers (Chrome 14+, Firefox 29+, IE11+) implement EcmaScript 402 Internationalization API so you can do something like str1.localeCompare(str2, locale), see this article.
The real problem occurs when you want to compare two strings case insensitive and accent insensitive for equality (as oppose for ordering like in case of sorting). Basically, there is no way (and this is true even in "big" programming languages like Java or C#).

Time Zone Sensitive Date and Time Display in Web Applications?

I am looking for recommendations on displaying times in a web application in a time zone other than the user's current time zone.
We store our dates/times in UTC/GMT in the database, so it is not an issue to format the time for UTC/GMT or the user's current time zone. However, in other situations we need to display the time from the point of view of an arbitrary time zone (i.e. every date/time on this page is in Eastern, regardless of whether or not the user is in West Coast, Central, Eastern, etc.).
In the past we have stored offsets or time zone info, then done the calculations in server code in .Net or else we have done some client-side manipulations in javascript that I would prefer to avoid, since it all becomes very dependent on javascript and the user's browser. I'd like to know the best way to do this in a more client-side/MVC type application.
Here is an example:
Date stored in db: 1302790667 (Thu, 14 Apr 2011 14:17:47 GMT)
Converted date displayed for a client in Central time zone: Thu Apr 14 09:17:47 2011
Date I actually want to display, always in Eastern time zone: Thu Apr 14 10:17:47 2011
In the above example, it's easy to get the time in UTC (#1) or the user's current time zone (#2) but it is more difficult to get #3. My options seem to be:
Store offsets or time zones in the db and do calculations on the client - this is what we've done in the past with .Net but it seems even messier in client side code is the path we are currently trying to avoid.
Do the conversion on the server and send down a full date for display to the client - client receives a string ("Thu Apr 14 10:17:47 2011"). This works but it's not very flexible.
Do the conversion on the server, break it into parts and send those down to the client, then put them back together. ("{DayOfWeek:Thu, Month:Apr, Day:14, Hour:10, Minute:17}"). This gives us the correct data and gives us more flexibility in formatting the date but it feels a little wrong for this scenario.
Any other options ideas? How do others handle similar situations? Thanks.
Our results:
I tried out a few libraries like Datejs, MS Ajax, etc. and I was never very happy with them. Datejs didn't work at all in a few of my test cases, is not actively maintained, and seemed to focus a lot on syntactic sugar that we don't need (date.today().first().thursday(), etc.)
We do use jQuery for some basic date/time parsing.
I came across a lot of "roll-your-own" client-side date conversion "hacks", most of which only addressed the conversion to UTC, started off working fine, and then eventually fell apart on some edge case. This one was the 90% solution for a lot of standard UTC conversion but didn't solve our "arbitrary timezone" issue.
Between the code complexity the conversion routines added and the bugs they seemed to cause, we decided to avoid client side date processing most of the time. We do the date conversions on the server with our existing date handling routines and pass the formatted dates or info down as properties to be used by the view. If we need a separate date, we just add another property. There are usually only a few properties that we need at a time (i.e. EventDateUTC, EventDateLocal, EventDateAlwaysAustralia, and EventDayOfWeek).
I offer the suggestion that you look into the Datejs library. It offers a bunch of extensions to basic JavaScript date manipulation, including a "setTimezone()" method and flexible ways to convert a date into a formatted string for display.
I usually hesitate to suggest libraries when their use is not explicitly allowed for in questions, but Datejs isn't very large and it's pretty solid (even though it's called an "alpha" release). If you'd prefer not to rely on something like that, you might want to look at it anyway just to see the basics of how its extensions were implemented.

Multiple date compare in javascript

I am trying to validate, get and compare 2 dates.
The dates are coming from 2 text inputs and are currently formatted as the following example: 17/01/2011 00:00
How do I convert that string to a date using the Date object?
I'm trying to validate it under these terms:
Date must be in the correct format (17/01/2011 00:00)
Date must be in the future (How do I do that considering JS runs on Local and date can be set incorrectly on the user's machine?
First date must be before second date. (it's a from_date -> to_date input).
Can you please assist?
Thanks,
A slightly different approach,
If it is not too late, you can enforce the validity of the date by providing a date / time selection control that will output the date in the format that you required (There should be quite a lot of them out there, see this or this for some. In this way, you don't have to rely on the user to input the date in a textbox where they can input whatever they want. If this is not possible, you can try looking at the input masking that might help the user input the date more accurately in a textbox format, for example see: this or even this that will allow you to input string like "today", "2 weeks from now", etc. This will increase the usability aspect of the form.
You might have to revalidate the date on the server side for this. It's always a good idea to double check user inputs both at client side and again in server side. But for client side validation, you can try the datejs libray i mentioned above or create one as per suggestion from Stefanos.
Already answered this in #2.
Hope that helps.
As for the format validation you can use a regex to do it.
To get the current time you need to request the data from a server. One option is from the one your users get the web pages using a backing language (php, java, ...). One other option is to request the time from a time server with an http request. The answer could be simle text or an XML, or you may need to communicate with another protocol, like SOAP.
To compare the 2 dates you can convert them to milliseconds and then simply compare the values. Also the JavaScript object Date can be helpful for conversions and comparisons.
You cannot manipulate times and dates without knowing the time zone.
If a string representation of a date does not include the GMT offset, you have to guess the time-zone, unless you add a rule to account for it, or only want the date to be within a day or so accurate.

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