Display HTML5 DateTime-local base on User's Locale/Culture - javascript

How to display the value of this base on user's locale/culture?
Right now it displaying US format (mm/dd/yy) and I need UK format (dd/mm/yy).
I would also like to display base on thes user's locale format or detect where's the user's locale.
Something like the javascript toLocaleString().
<input type="datetime-local" value="">

That is not supported by browser yet. See following post.
http://weblog.west-wind.com/posts/2012/Nov/08/HTML5-Input-typedate-Formatting-Issues.
So you need to manage it via server side code for example If you want to do it with ASP.NET here is the post which will help you.
http://msdn.microsoft.com/en-us/library/bb882561(v=vs.110).aspx
For JavaScript, you need to use tolocalstring as you have mentioned in your question.
http://www.w3schools.com/jsref/jsref_tolocalestring.asp

navigator.isBritish=(function(){
return new Date('12/6/2009').getMonth()===5;
})();
Handy for setting up the order of inputs and date displays, anyway.

Related

How to detect date format defined by browser?

I'm using HTML5 input type=date field and because some browsers still don't support this feature, I would like to create error validation message for browsers that display just normal text field instead of date field. This error message should look like
Please enter date in format: ...
But I need to find the correct format, that the browser is set to. Is there any php/js/jQuery way how to find out this?
Thanks to #Jose Vega's answer I was able to find very easy way how to do it.
var now=new Date(2013,11,31);
var str=now.toLocaleDateString();
str=str.replace("31","dd");
str=str.replace("12","mm");
str=str.replace("2013","yyyy");
Error message:
"Please enter date in format:" + str
I have used the globalize library to do something similar. I don't know if its functionality has what you are looking for, but I know it does a good job handling different cultures. I use the window.navigator.userLanguage to determine culture and then feed it to the globalize library to do its thing. I've had success when dealing with currency and numbers.
EDIT: See if this helps:
var now=new Date();
alert(now.toLocaleString());
taken from How format JavaScript Date with regard to the browser culture?
Reference Displaying proper date format depending on culture
Why not to allow users to enter date in any format they like.
E.g. i am tourist in the USA and the browser says me to use format mm/dd/YYYY instead of my native dd.mm.YYYY.
Just get any date entered by users and parse it with Date.parse()

Why would I use input type date in a regular web application?

I am currently building an iOS App using Phonegap and jQuery Mobile, and I am using the HTML5 input type date element, for the user to enter their birthday. This makes total sense for a Phonegap app to use, because this invokes the phones native datepicker - thats great!
However, when using a desktop browser to test out my app (I am using Firefox 16), no datepicker is shown, obviously due to the fact that Firefox has not implemented this yet. Thats cool, except for the fact that I can enter whatever I want into that field - any format I want.
The specification says that it should use the yyyy-mm-dd format, and my iOS device does that. But, if I enter e.g 06-09-94, that won't play nicely when I try to convert it to a JavaScript Date Object.
Here are my tests:
// Value is set to 1994-09-06
console.log(new Date($("input[type=date]")[0].value));
// > Date object representing September 6, 1994
// Value is set to 06-09-1994
console.log(new Date($("input[type=date]")[0].value));
// > Invalid date
I've read somewhere that internally (atleast for chrome), all "valid" date formats will be represented as yyyy-mm-dd, but that's not happening. http://updates.html5rocks.com/2012/08/Quick-FAQs-on-input-type-date-in-Google-Chrome
What kind of format does the input value return?
The input.value always returns as yyyy-mm-dd regardless of the
presentation format.
So, as the title suggests: Why would I want to use an <input type="date"> in a non-mobile based web application?
You would want to use the HTML 5 form elements because there is hope that one day all major browser support them. As you noticed, datepickers etc offer really great functionality out of the box, which would have to be coded by hand otherwise.
You wouldn't want to just let them stand on their own, though, in environments where you have no controller over what browser the user is using.
The suggested way to handle this at the moment is to check, if the browser supports the required form field, if not, use an alternative like a jQuery UI element.
Quickly googled tutorial: http://www.javascriptkit.com/javatutors/createelementcheck2.shtml
I think, some of the js framework handle such a check internally, at least for dojo I know that they try to use as much native browser functions as possible - but I'm not sure how it is handled with datepickers.
I have to say, I'm surprised firefox hasn't implemted this yet, Chrome and Opera seem to lead the way....
Since not all browsers still support all HTML5 features you can't see all it's benefits right away.
The <input type=date> tag is one of those features, if you run the code in the Chrome browser it will open date picker, when you can choose the date by clicking on the arrow button. This feature is missing though on Safari browser. Just wait for updates of browsers.
You check that the value is in an appropriate date format before trying to convert it to a Date object.
If it isn't, display an error message to the user instead (e.g. by adding a <label> by the <input> or using an alert).

Mobile HTML5 App - determining a users date/time preferences?

Is there any way via HTML5, proprietary apis, or PhoneGap to obtain the date format a given user is likely to want?
I currently display everything as MM/dd/yyyy, but this is confusing for any users who live in dd/MM/yyyy countries.
I believe you will want to look into the Globalization plugin's getDatePattern method.
https://github.com/phonegap/phonegap-plugins/tree/master/Android/Globalization
https://github.com/phonegap/phonegap-plugins/tree/master/BlackBerry/Globalization
https://github.com/phonegap/phonegap-plugins/tree/master/iPhone/Globalization
The simplest way to determine the local day-month/month-day order is to check it.
You can check once and save it as a boolean to use in any input or output date formatting.
(this returns true if the date should precede the month- feel free to reverse it!).
Date.datefirst= (function(){
return Date.parse('2/6/2009')> Date.parse('6/2/2009');
})()

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