How do you globally set the date format in ASP.NET?
My local machine and servers have Regional Settings set to "English (New Zealand)".
When I format a date with dd/MM/yyyy I expect to see 19/11/2008 for today for example.
Until recently, that is what I did in fact get from both my local machine and the servers.
Just recently, for some mysterious reason, our local machines have changed ever so slightly. Despite still be set to "English (New Zealand)", the date delimter has changed from / to -! The same change has not occurred on the servers which still show "English (New Zealand)" and the / for the date delimter.
So now for my local machine, for the format dd/MM/yyyy I get 19-11-2008 instead of 19/11/2008.
This is a little disconcerting.
The only way around it that I can see so far is to escape the slashes and set the format to dd\/MM\/yyyy. It seems to work, but it doesn't seem to be the ideal solution.
Can anyone please help?
NOTE: This is for an intranet application and I do not care about true globalisation. I just want to fix the date format and not have it change on me.
You can change the current thread culture in your Global.asax file, and override the date format for example:
using System.Globalization;
using System.Threading;
//...
protected void Application_BeginRequest(Object sender, EventArgs e)
{
CultureInfo newCulture = (CultureInfo) System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
newCulture.DateTimeFormat.ShortDatePattern = "dd-MMM-yyyy";
newCulture.DateTimeFormat.DateSeparator = "-";
Thread.CurrentThread.CurrentCulture = newCulture;
}
In web.config, set tag as per the following documentation
<system.web>
<globalization culture="en-NZ" uiCulture="en-NZ"/>
</system.web>
A good way is configure the Web.Config, the date format appear in all components of a aspx
<system.web>
<globalization uiCulture="en" culture="en-NZ" />
</system.web>
You can set your culture without manipulation:
using System.Globalization;
using System.Threading;
//...
protected void Application_BeginRequest(Object sender, EventArgs e)
{
Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-NZ");
}
It is an old post, but I thought it might be useful to mention it here, my problem was something like what the OP has asked, but the solution was that the culture was changed in the IIS, not from control panel.
IIS has it is own culture selection, which by default will follow the local computer culture. But for some reason, it was changed to a different culture, and I started getting those weird date formats.
You can look for more answers here.
For format strings, the format character / does not actually resolve to the literal "/" as you would expect. Instead, it resolves to the current date time separator as configured in your regional settings. Try changing the DateTimeFormatInfo.DateSeparator property.
For more information, see: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Related
For background, we are in the process of upgrading to Windows Server 2012 R2, and testing revealed that some date input textboxes on our ASP.NET site aren't working as intended. The textboxes have a CompareValidator defined for them to check if one date is later than the other.
<asp:CompareValidator ID="CompareValidator3" runat="server" ControlToCompare="txtStartDate"
ControlToValidate="txtEndDate" ErrorMessage="..." Operator="GreaterThan" Type="Date"
Display="Dynamic"></asp:CompareValidator>
This CompareValidator is failing all the time now, on Windows Server 2012, whereas the old site hosted on Windows Server 2008 did not have this problem. I have done some digging and I think the most likely culprit is the change in default date format for the Canada region in Windows Server 2012. In the generated code for the page, the DOM element for the validator has a property "dateorder" that's always being set to "ymd". This value is "dmy" on the old site.
...
cutoffyear: "2029"
dataset: DOMStringMap
dateorder: "ymd"
dir: ""
display: "Dynamic"
...
Because our inputs take date strings like "01/01/2015", the "ymd" pattern is not matched and the validator returns false. I have changed the date format settings everywhere that I can think of, and even tried changing the IIS site's .NET Globalization settings to use another culture (en-GB), and nothing has worked. I'm really curious as to where this "ymd" setting comes from, and how to change it. Any help is greatly appreciated. Thanks!
"dateorder" comes from BaseCompareValidator which essentially reads CultureInfo.CurrentCulture
DateTimeFormatInfo dateTimeFormat = CultureInfo.CurrentCulture.DateTimeFormat;
string pattern = dateTimeFormat.ShortDatePattern;
string dateorder = (pattern.StartsWith ("y", true, Helpers.InvariantCulture) ? "ymd" : (pattern.StartsWith ("m", true, Helpers.InvariantCulture) ? "mdy" : "dmy"));
Now the gotcha as pointed here, is that Regional Settings is per-user and you might want to check the account the Application Pool was running under.
Maybe somebody changed the date format in the Windows OS on the old computer? But how about trying to force it within your application...my idea is to do it in the Global.asax file (you may have to add that file to the root of the application if it is not already there). Then, something like this:
using System.Globalization;
using System.Threading;
protected void Application_BeginRequest(Object sender, EventArgs e)
{
CultureInfo myCulture = (CultureInfo) System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
myCulture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy";
myCulture.DateTimeFormat.DateSeparator = "-";
Thread.CurrentThread.CurrentCulture = myCulture;
}
Have you try to change sort date from control panel regional setting. Dateorder and cutoffyear etc attribute are used by validation JavaScript generated by .net for validator control to function on browser. Value of these comes from server settings. IIS only picks as per server config and generats HTML.
My web app is running perfectly in asp vb.net editor. But when i run my web app through IIS7 then i get this error. What am i missing in configuring IIS7? Is there anyone who can suggest something?
Thanks in Advance
Because your IIS7 is configured for the English Language and that date is probably Italian or something similar. You'll have to tell to the Date.Parse which culture to use.
Something like
dateValue = Date.Parse(yourDate, CultureInfo.CreateSpecificCulture("it-IT"))
Or you can change the culture in your IIS7
Here there are the instructions
for example if you use the UI
Using the UI Open IIS Manager and navigate to the level you want to
manage. (omissis)
In Features View, double-click .NET Globalization.
On the .NET Globalization page, in the property sheet, click to select
the global setting you want to edit, and select a value from the
drop-down list.
In the Actions pane, click Apply.
Or you could set the culture of your app in the web.config
<system.web>
<globalization culture="it-IT" uiCulture="it-IT"/>
</system.web>
If you are sure that the date is always in exactly that format, then you can use ParseExact instead:
var date = DateTime.ParseExact(
"31/03/2012",
"dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
You can also use the CDate function to parse the date.
Dim dDate As Date = CDate("31/03/2012")
The advantage of using this function over the DateTime parsing functions is that you can feed it any acceptable format of date string and it will convert it. It will throw an error if it can't parse the date.
I have an HTML home page. I want to be able to output to a text document on the server every time a person views the page.
I want to out put the IP addrs, Page and Date/Time anyone know an easy way of doing this?
If it has to be done other than html i would prefer to use ASP.
First, rename the page to have .aspx extension and add code behind file as well.
Second, add this method to the code behind:
private void WriteLog()
{
string currentFileName = Path.GetFileNameWithoutExtension(Request.FilePath);
string logFileName = string.Format("{0}_{1}.log.txt", currentFileName, DateTime.Now.ToString("ddMMyyyy"));
string logFilePath = Server.MapPath(logFileName);
string IP = Request.ServerVariables["REMOTE_ADDR"];
string logMessage = string.Format("[{0}] [IP: {1}] [Page: {2}]", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"), IP, Request.FilePath);
File.AppendAllLines(logFilePath, new string[] { logMessage });
}
And finally just call the above method from within the Page_Load event e.g.
protected void Page_Load(object sender, EventArgs e)
{
WriteLog();
}
This will create text file with the same name as the .aspx (in the same location) plus the current date to avoid clogging the same file with millions of lines, and append one line for each hit.
Edit: this is .NET 4.0 code so you'll have to define this as the target framework in both Visual Studio in case you're using it, and in the IIS configuration. The web.config should be updated by the Studio and in case you're not using it, here are the extra lines:
<system.web>
<httpRuntime requestValidationMode="2.0" />
<compilation debug="true" targetFramework="4.0" />
</system.web>
As #Alp said PHP would be the way to go:
$_SERVER['REMOTE_ADDR']; //gives you the visitor's IP address
basename($_SERVER["SCRIPT_NAME"]); //gives you the page name
date(); // gives you the current date
Then it would just be a case of running a little script that writes those to a file on each page.
Might be worth looking at Google Analytics - it gives lot's of useful stats about visitors (not 100% you can get individual IP addresses, can anyone clarify this?)
Edit:
ASP.NET
Request.ServerVariables["REMOTE_ADDR"]; // ip
Request.ServerVariables["HTTP_REFERER"]; // page
You can use PHP for that if your server supports it.
You can use an existing log framework like Log4Net.
I have a TextBox in an Asp.net form. there is a simple javascript witch separates each three digits in TextBox. it works fine when you enter data in TextBox. I used coma , for separating digits and used dot . as floating point character.
as I said every thing works fine when I am entering data in TextBox. but when the post-back occurs and saved data returns to client, every .(s) has been removed (for example 2.3 saved as 23 and digits in TextBox are separated by . instead of ,.
this problem occurs just in a specific server (windows server 2003 sp1) and works fine in other windows server 2003 (SP1)! I am experiencing this problem for first time!
But I think the problem is because of specific Regional & Language Options in the server. This server is joined to a domain controller. when I change the regional and language options to this set:
Decimal Symbol -> .
Digit Grouping Symbol -> ,
nothing changes.
when I check the following item after customizing settings :
Apply All Settings to the current user account and to the default user profile -> checked
when I restart the Server, It jumps out from domain and need to be re-joined to domain controller! and of-course nothing changes again!
Do you had this problem? any solution please!
I can not post code here, because the code is too complex and I am sure problem is not because of code because it is working every where unless the specified server.
EDIT
Also setting regional and language options for network service user may help to solve the problem. any body knows how can I do this ?
Have you tried using the globalization tag in your web.config? This prevents you from running into trouble when multiple servers are configured differently (ie. different languagepacks).
<configuration>
<system.web>
<globalization
culture="en-US"
uiCulture="en-US" />
</system.web>
</configuration>
After goofing around with a similar problem for WAY to long I did the following with the help of a number of clues (also found on StackOverFlow, StackOverFlow rocks by the way...)
The first thing I did was dump out what the server was actually thinking (Page_Load):
var dtInfo = System.Globalization.DateTimeFormatInfo.CurrentInfo;
DisplayDebugInfo(String.Format(
"Culture({0}/{1}), DateFormat(SD:{2},DS:{3})",
System.Globalization.CultureInfo.CurrentCulture.Name,
System.Globalization.CultureInfo.CurrentUICulture.Name,
dtInfo.ShortDatePattern, dtInfo.DateSeparator));
Also on Windows 2003, I tried fixing the regional setting via the regular control panel but with no success.
I also tried setting the globalization settings in the web.config as mentioned in the other solution but with little effect.
It seems that once you start messing with the regional setting you can quickly get to the point where things are messed up. I decided to avoid messing with the registry and go for a code solution because then I would not have to worry when my code was released to production.
I added the following code to the base class for my page so that it would fix it everywhere. You could also place it in the Page_Load.
using System.Globalization;
using System.Threading;
// Fix the cultural settings...
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
culture.DateTimeFormat.DateSeparator = "/";
Thread.CurrentThread.CurrentCulture = culture;
Problem solved. For me anyway.
I am building a web-store that uses URL encoding extensively.
I have a list of Departments & Categories in my database which I use to generate the links. These are, of course, URL encoded before they are sent.
Some Typical Links are...
/MySite/Store/Countertop+Equipment/Can+Openers.aspx
/MySite/Store/Dinnerware.aspx
/MySite/Store/Kitchen/Pastry%2f+Decorating.aspx
In my HTTPHandler I call app.Request.Path to obtain the current path. The string returned by this call is no longer URL encoded which is making it impossible for me to parse correctly.
Once the URL encoding is lost
/MySite/Store/Kitchen/Pastry%2f+Decorating.aspx becomes
/MySite/Store/Kitchen/Pastry/Decorating.aspx.
This is obviously breaking the method that converts the URL to a QueryString.
Anyone know how to fix this?
Here is the core of my HTTPHandler
public void Init(System.Web.HttpApplication app)
{
app.BeginRequest += new EventHandler(Application_BeginRequest);
}
private void Application_BeginRequest(object sender, EventArgs e)
{
System.Web.HttpApplication app = (System.Web.HttpApplication)sender;
string realUrl = GetRealUrl(app.Request.Path);
if (!String.IsNullOrEmpty(realUrl))
app.Context.RewritePath(realUrl, false);
}
I really appreciate your help!
You cannot use Request.Url (including Url..PathAndQuery, AbsolutePath etc) as its OriginalString is already decoded.
So there is no point to use Request.Url at all and you can try to play with following:
Request.AppRelativeCurrentExecutionFilePath
Request.CurrentExecutionFilePath
Or in a worst-case scenario you'll need to parse the Url:
[Test]
public void RewriteProoveOfConcept() {
var path = #"/MySite/Store/Kitchen/Pastry%2f+Decorating.aspx";
var res = Regex.Replace(path, #"/(.+)/(.+)/(.+)/(.+)\.aspx", #"/$1/YourPage.aspx?category1=$2&category2=$3&category3=$4");
Assert.AreEqual(#"/MySite/YourPage.aspx?category1=Store&category2=Kitchen&category3=Pastry%2f+Decorating", res);
}
This shows how you can get the URL:
/MySite/YourPage.aspx?category1=Store&category2=Kitchen&category3=Pastry%2f+Decorating
from:
/MySite/Store/Kitchen/Pastry%2f+Decorating.aspx
Additionally consider using Routing instead of UrlRewrite.
Cheers,
Dmitriy.
Try the AbsolutePath or PathAndQuery properties on the Request object. Both of them should maintain the url encoding.
You can UrlEncode the URL before parsing it. Or better yet, keep URL's non-encoded in database. You don't even need to encode them if you use HyperLink control.
It turns out that the issue is occurring in IIS before .Net even gets its hands on the request. It appears that this is a dead end.
An additional word of warning is that my IIS test server (XP) was rejecting requests containing encoded amperstands as a security risk and could not be persuaded to cooperate with anything short of a registry edit. Not sure if this goes for all versions, but even if a server variable can be retrieved this seems like another good reason to use a different tactic.
Here is the follow-up question with the accepted solution-
ASP.Net URL Encoding