Displaying proper date format depending on culture - asp.net

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.

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:
Walkthrough: Globalizing a Date by Using Client Script

See toLocaleString and related functions.

If you control the backend, why not just send a timestamp and push it into Date object?
As for formatting on the client side, since I was already using Dojo, I solved this problem by using dojo.date.locale.format. It was completely painless.
Locale is detected automatically or can be set arbitrarily.
Shorthand format options (e.g.: long short)
Data selectors (e.g.: time, date)
Ability to specify an arbitrary date/time pattern (probably not application to this application, but still useful).
Tutorial: http://docs.dojocampus.org/dojo/date/locale
API doc:
http://api.dojotoolkit.org/jsdoc/1.3/dojo.date.locale.format
Date format descriptions: http://www.unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns

Three things you could use:
1) toLocaleString - As suggested already. The problem with this is when sending a string of "4/1/2009" this can result in a couple things. January 4 or April 1.
2) navigator.language and navigator.systemLanguage - After you get the date string you can check to see what language the system is in and parse the date from there. The problem with this and solution 1 is what if you have a UK server and the browsers machine is US. You will have the code behind sending April 1 as 1/4/2009 where the javascript will read the string as whatever language the clients browsers is. So, UK server and US browser will give you a wrong result.
3) Use Code Behinds Culture - Create a variable in your javascript that when the page loads, it will call a function in your code behind that returns this.Page.Culture from there, you will know what culture the string is being sent back as. This will eliminate the mismatch that the first two solutions can cause. It will take a little extra work to make sure it's displayed correctly but at least you will be able to use the string without having the possibility of mismatching cultures.

toLocaleDateString would be a better solution than toLocaleString for your problem as it doesn't include the time (as you only are requesting the date).

The open-source JavaScript library Date.js has some great methods for formatting dates, as well as it supports a bunch of languages:
Date.js at Google Code: http://code.google.com/p/datejs/
If you want nicely formatted dates / times, you can just pass a formatting string (nearly identical to those used in .NET Framework) into any Date object's .toString() method.
It also has a whole set of cultures which allow you to simply include the appropriate script for that culture.
If you want to manage that yourself (as we do in our apps), you can find resources which give you the list of appropriate resource strings for a given culture. Here's one that shows proper formatting strings for a ton of cultures: http://www.transactor.com/misc/ranges.html

As you are using ASP.NET then you may also be using ASP.NET Ajax. If so, there are two properties on the ScriptManager that are of use to you:
EnableScriptLocalization - Gets or sets a value that indicates whether the ScriptManager control renders localized versions of script files.
EnableScriptGlobalization - Gets or sets a value that indicates whether the ScriptManager control renders script that supports parsing and formatting of culture-specific information.
<asp:ScriptManager ID="AjaxManager" runat="Server" EnablePartialRendering="true"
EnableScriptGlobalization="true" EnableScriptLocalization="true" />
When you enable both of these (set to true) then ASP.NET Ajax extenders etc. should automatically be localised into the culture specified in web.config:
<configuration>
<system.web>
<globalization
fileEncoding="utf-8"
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="en-GB"
uiCulture="en-GB" />
</system.web>
</configuration>
For instance, setting this will localise the AjaxControlToolkit Calendar into your specificed culture.
Even if you are NOT using ASP.NET Ajax adding a ScriptManager and enabling localisation will give you a useful javascript variable called __cultureInfo that contains a JSON array of localised formate, such as currencies, dates etc.
"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":1,"CalendarWeekRule":0,"FullDateTimePattern":"dd MMMM yyyy HH:mm:ss","LongDatePattern":"dd MMMM yyyy","LongTimePattern":"HH:mm:ss","MonthDayPattern":"dd MMMM","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH\u0027:\u0027mm\u0027:\u0027ss etc....

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).

Related

Datetime.Now method in ASP.NET

I am using ASP.NET to provide some variables for the data that has to be added to a SQL database.
Code I am using:
I am using DateTime.Now to select the current time.
How I use it:
I have two pages, one is a page to insert the posts of the users. Other page is used for ajax purpose, to add some text comments to the posts.
In both page I use the same code.
But the code is executing different values. You can have a look here:
In the post the time is saved as "9/1/2013" which means 1st September, 2013! In comment it is saved as Sep 1 2013, which means the same.
My question: how does the code know that the request is an ajax one or the post one. The post page code is wrapped in if(IsPost) { however the comment is an ajax call.
What is the reason behind this?
I found what the issue was.
I had set the column DataType to nvarchar(50) in the database table. After editing it to DataType DateTime I was able to get the same result. So the issue was not the Culture or DateTime. It was the DataType of the column in SQL Server Database.
Assuming that your AJAX call is not changing the format string of your DateTimes, I would assume the threads which process those 2 different requests are operating under different cultures, which would explain why they're being displayed differently (not sure why though, check your settings perhaps). Try the following and you'll see how culture can effect DateTime output:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine (DateTime.Now.ToString());
Thread.CurrentThread.CurrentCulture = new CultureInfo("gu-IN");
Console.WriteLine (DateTime.Now.ToString());
Here's some additional information on CultureInfo.
Code knows from Current thread's Culture information. You should use DateTime.Now.ToString("yyyy-MMM-dd") or any other formate according to your needs to be sure of output.

How to pass value from web form to another web form?

Can anybody tell me how to pass a value from one web form to another web form without using a query string and session?
You can pass the Values over different pages via QueryString like:
Response.Redirect("yourNextpage.aspx?identifier=DesiredValue");
On your next page you can retrieve the value like this:
Request.QueryString["identifier"];
Other Preferred way would be Server.Transer() and Postbackurl.
Refer this link for various possible ways.
there are several ways you can pass parameters between pages.
Using a Query String
Getting Post Information from the Source Page
Using Session State
Getting Public Property Values from the Source Page
Getting Control Information from the Source Page in the Same Application
for more detail visit followng link.
http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
You could use a Querystring in this case:
Page.Response.Redirect("show.aspx?id=1");
And then read it on the other end:
int id = Page.Request.QueryString["id"];
Using PostBackURL, ex:
PostBackUrl="~/result.aspx"
and on result.cs (Page Load)
lblEmployeeNumber.Text = HttpContext.Current.Request.Form["txtEmployeeNumber"];
With Session:
For example you login the system and your id is 123123123.
string userid = 123123123;
Session["userid"] = userid;
When you go another page/pages your session is alive when your session timeout.
<system.web>
<sessionState timeout="1250"/>
</system.web>
It seems what you're looking for is something like the flash-, view- or conversation scope in Java EE and Ruby on Rails.
For ASP.NET you could perhaps take a look at this one: Is there an equivalent of JSF #ViewScope in ASP MVC?
depends on type and how much information you wish to transfer. for instance, if you want to transfer some variable (strings or integer values) you consider to use querystring (you can found here major information). for instance, if you want to transfer typed objects (class instance) you consider to use session (you can found here major information).

dates behaving differently on different dbs?

I have an asp.net webpage, with a jQuery datepicker on it.
I am in the UK, so when I enter 28/02/2010, I expect it to resolve to 28th Feb 2010.
This is working as expected on my local dev env - but not on our QA or prod-like envs - or one of the other dev machines. In these cases it seems to attempt to resolve it to American date format - and fails validation as it is out of range.
The jQuery seems to generate the correct date each time - which leads me to think it may be a database issue.
I am using SQL Server 2005, my collation is Latin1_General_CI_AS, my colleagues are using collation SQL_Latin1_General_CP1_CI_AS, and a Chinese one.
Given that we don't have control over the prod SQL Server installation (just our db), what is the best way to make this work in a standard way? Change the db settings, or the code that uses it?
Thanks in advance!
- L
[EDIT to add code info]
This is my view code to call the datepicker:
<%=Html.TextBox("DateOfBirth", Model.DateOfBirth.ToShortDateString(), new { #class = "datepicker" })%>
Here is the js for the datepicker:
DatePickerSettings = {
setup: function () {
$(".datepicker").datepicker({
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true
});
}
};
And this is how I specify the date in the model:
[Required]
[DisplayName("Date of Birth")]
public virtual DateTime DateOfBirth { get; set; }
The date appears correct inthe controller and repository... until it hits the db.
Thanks :)
I was hoping to wait until you'd updated the question with some more information, but as I've seen some answers suggesting that you change the string format you use to talk to the database...
Don't send dates as raw text in SQL queries.
Use a parameterized query, which means you don't need to worry about formatting the value at all. Then you've just got to make sure that you can get the date format correct between the browser and ASP.NET.
Aside from anything else, if you're including user data in SQL queries directly, you'll generally be opening yourself up to SQL injection attacks. Always use parameterized queries (unless your web app is really a "run this SQL" test tool...)
If you're already using parameterized queries, then the problem is likely to be between the browser and ASP.NET, and the database part is irrelevant. Divide and conquer the problem: chase the data as it passes through different layers (browser, jQuery, ASP.NET etc) until you find out where it's gone wrong. Don't even think about a fix until you know where it's gone wrong.
Is your page Culture aware?
You can determine UI Cutlure information for different browsers(locales) and have your ASP.NET Culture constant.
The Culture value determines the results of culture-dependent functions, such as the date, number, and currency formatting, and so on. The UICulture value determines which resources are loaded for the page
Check out this MSDN link:
How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization
http://msdn.microsoft.com/en-us/library/bz9tc508(v=VS.85).aspx
Use CONVERT to change the date format to a standard that is accepted across all environments.
CAST and CONVERT
I'd have to see the code that interprets the dates to know for sure, but a likely suspect is the Region and Language settings on the machines where the code is running. Make sure it is set appropriately for your region.
However, if you can't change settings on the servers, you should probably explicitly use CAST or CONVERT in SQL Server to force it to parse it in the region specific way you expect the data will be entered.
You also need to check your ASP.Net layer, and see what it is running in.
Check the machine configuration and check they are set to run in the same date/time/region.
Change your code to use yyyymmdd format.
As far as i know it works in all the DBs
Just to add another opinion here, I find dd/mmm/yyyy the best date format to send to databases as it's completely unambiguous across cultures.

Why does Html.DisplayFor and .ToString("C2") not respect CurrentUICulture?

In my ASP.MVC 2.0 website I have the following setting in web.config:
<globalization uiCulture="da-DK" culture="en-US" />
When I try to display an amount in a view using Html.DisplayFor() or ToString("C2") I expected to get "kr. 3.500,00" (uiCulture) and not "$3,500.00" (culture).
<%:Html.DisplayFor(posting => posting.Amount)%>
<%:Model.Amount.ToString("C2")%>
If I explicit uses CurrentUICulture info it works as expected, but I don't want to do that everytime I need to display a number, date or decimal. And I also like to use DisplayFor, which doesn't support the IFormatProvider parameter.
<%:Model.Amount.ToString("C2", System.Globalization.CultureInfo.CurrentUICulture)%>
How can I change the formatting, without changing the culture of the system?
This is running in Azure, and if I change the culture to "da-DK" all decimal points are lost, when saving to Azure Table storage! #BUG
The UI culture is used to lookup and load resources, the Culture is used for formatting.
So the various ToString(string) and String.Format overloads that don't take a culture will use the thread's current Culture (System.Globalization.CultureInfo.CurrentCulture) to format.
If you want to use Danish formatting for currency, dates, ... then Thread.CurerentThread.CurrentCulture needs to be set to CultureInfo.GetCultureInfo("da-DK") (directly or indirectly).
Summary: you have Culture and UI Culture the wrong way around.

Best way to convert a decimal value to a currency string for display in HTML

I wanting to show prices for my products in my online store.
I'm currently doing:
<span class="ourprice">
<%=GetPrice().ToString("C")%>
</span>
Where GetPrice() returns a decimal. So this currently returns a value e.g. "£12.00"
I think the correct HTML for an output of "£12.00" is "£12.00", so although this is rendering fine in most browsers, some browsers (Mozilla) show this as $12.00.
(The server is in the UK, with localisation is set appropriately in web.config).
Is the below an improvement, or is there a better way?
<span class="ourprice">
<%=GetPrice().ToString("C").Replace("£","£")%>
</span>
Try this, it'll use your locale set for the application:
<%=String.Format("{0:C}",GetPrice())%>
Use
GetPrice().ToString("C", CultureInfo.CreateSpecificCulture("en-GB"))
The £ symbol (U+00A3), and the html entities & #163; and & pound; should all render the same in a browser.
If the browser doesn't recognise £, it probably won't recognise the entity versions.
It's in ISO 8859-1 (Latin-1), so I'd be surprised if a Mozilla browser can't render it (my FF certainly can).
If you see a $ sign, it's likely you have two things:
1. The browser default language is en-us
2. Asp.net is doing automatic locale switching. The default web.config setting is something like
<globalization culture="auto:en-us" uiCulture="auto:en-US" />
As you (almost certainly) want UK-only prices, simply specify the locale in web.config:
<globalization culture="us" uiCulture="en-gb" />
(or on page level:)
<%#Page Culture="en-gb" UICulture="en-gb" ..etc... %>
Thereafter the string formats such as String.Format("{0:C}",GetPrice()) and GetPrice().ToString("C") will use the en-GB locale as asp.net will have set the currentCulture for you
(although you can specify the en-gb culture in the overloads if you're paranoid).
You could write a function which would perform the conversion from price to string. This way you have a lot of control over the output.
The problem with locale is that it's web server dependent and not web browser dependent.
If you need to explicity state the localisation you can use the CultureInfo and pass that to the string formatter.
just use the ToString("C2") property of a decimal value. Set your globalization in the web.config - keep it simple.

Resources