Displaying proper date format depending on culture

2019-02-14 08:02发布

I am using a control for a popup calendar date picker. This uses a javascript function, SetText, to set the textbox to the given date. I can't change anything in the calendar control itself but I can override the SetText function. The SetText javascript just takes the TextBox name and the date value in string format and sets the TextBox to the string.

The problem: I need to display the date in the format "April 30".

Easy to do. Use getMonth() and getDate() where I can parse the information from there.

Now, I need to make sure this shows correctly for different cultures. For example, the UK shows dates as "30 April". Since the code-behind(c#) could be sending the date in the UK format how do I know in the javascript that they're using UK(dd/mm/yyyy) and not US(mm/dd/yyyy)?
The browsers navigator language could be set to one setting while the server is set to another to cause a January 4 as April 1 mismatch.

8条回答
甜甜的少女心
2楼-- · 2019-02-14 08:44

I solved this problem by using Datejs as

  • In codebehind(aspx.cs) I get the culture for an employee and add the appropriate js to the header as

string path = "http://datejs.googlecode.com/svn/trunk/build/date-" + GetCulture() + ".js"; Helper.AddJavaScript(this, path);

(in your case you can get the culture from navigator.systemLanguage (or navigator.browserLanguge etc) and add a script tag to the header with src attribute pointing to the appropriate path)

  • On the client-side I use

d.toString(Date.CultureInfo.formatPatterns.shortDate)

where d is any date object (I tried using Date.today().toShortDateString() but it was throwing exception. (the CultureInfo JSON object had a different structure than what the function expects).

查看更多
Melony?
3楼-- · 2019-02-14 08:45

You are using the Microsoft Ajax Framework, this framework defines a set of "client-side type extensions" which provide added functions or "extensions" to the JavaScript base types.

The Date Type Extensions is what you're looking for, specifically the Date.parseLocale function.

With this function you can parse a string, using a given format.

You can synchronize your server-side and client-side culture by setting the ScriptManager.EnableScriptGlobalization property to true, and use the Date.parseLocale function without specifying any format.

Give a look to this article:

查看更多
登录 后发表回答