C# / MVC
以 MM / DD / YYYY 格式生成datetime
,但有时我需要输入格式DD/MM/YYYY
。这是通过提供自定义格式完成的。但是,不是编写代码使C#生成日期时间DD/MM/YYYY
,而是我可以进行应用程序级别配置,例如web.config
,app.config
或machine.config
中的更改?
答案 0 :(得分:1)
尝试在Web.config中设置文化
<globalization culture="en-GB"/>
答案 1 :(得分:1)
如果你要做的只是在应用程序范围内设置日期格式,你可以在Web.config中设置文化
<globalization culture="en-GB" />
但是,如果您尝试减少重复代码,则可以更改当前线程的文化,然后在调用date.ToShortDateString()
后立即将其切换回来。这是一个CultureContext
类,它将仅在使用块内部更改格式。
/// <summary>
/// Allows switching the current thread to a new culture in a using block that will automatically
/// return the culture to its previous state upon completion.
/// </summary>
public class CultureContext
: IDisposable
{
public CultureContext(
CultureInfo culture,
CultureInfo uiCulture
)
{
if (culture == null)
throw new ArgumentNullException("culture");
if (uiCulture == null)
throw new ArgumentNullException("uiCulture");
this.currentThread = Thread.CurrentThread;
// Record the current culture settings so they can be restored later.
this.originalCulture = this.currentThread.CurrentCulture;
this.originalUICulture = this.currentThread.CurrentUICulture;
// Set both the culture and UI culture for this context.
this.currentThread.CurrentCulture = culture;
this.currentThread.CurrentUICulture = uiCulture;
}
private readonly Thread currentThread;
private readonly CultureInfo originalCulture;
private readonly CultureInfo originalUICulture;
public CultureInfo OriginalCulture
{
get { return this.originalCulture; }
}
public CultureInfo OriginalUICulture
{
get { return this.originalUICulture; }
}
public void Dispose()
{
// Restore the culture to the way it was before the constructor was called.
this.currentThread.CurrentCulture = this.originalCulture;
this.currentThread.CurrentUICulture = this.originalUICulture;
}
}
// Temporarily override the current thread's culture with the invariant culture
using (var cultureContext = new CultureContext(
CultureInfo.InvariantCulture,
System.Threading.Thread.CurrentThread.CurrentUICulture))
{
// All date formats here will be in the invariant culture
using (var originalCultureContext = new CultureContext(
cultureContext.OriginalCulture,
cultureContext.OriginalUICulture))
{
// All date formats here will be in the default culture
}
// All date formats here will be in the invariant culture
}
请参阅this answer以了解文化与UI文化之间的区别。