I develop multilingual site. Users can change preferred language, so i set current culture for each request like so:
System.Threading.Thread.CurrentThread.CurrentCulture = /* user preferred culture */
System.Threading.Thread.CurrentThread.CurrentUICulture = /* user preferred culture */
My domain entities have property DateAdded (to set the date the record was created):
public class EntityBase
{
protected EntityBase()
{
DateAdded = DateTime.UtcNow;
}
[Required]
public int Id { get; set; }
public DateTime DateAdded { get; set; }
}
My question is: how can i interact globally with all DateTime's in my WebApplication with Invariant Culture despite user's culture? I want to save DateTime's in database (im using Entity Framework), update them, calculate them, parse strings in invariant culture etc. I'll show DateTime in user's culture where it's needed only.
Well, my biggest problem was i set
CurrentCulture
too late. I set it in controller'sOnActionExecuting
method like so:But it is too late in some scenarios, i.e. ModelBinder binds data from POST request before any action is called.
I moved this logic up the request pipeline, i.e.:
This ensures culture is set as soon as possible for every request. After this i have no problems with converting strings to DateTime.