如何在ASP中本地化日期。NET MVC

时间:2022-11-01 04:12:51

We are working on an application which will be available to customers in multiple regions including the UK and US. On a number of the view pages we display dates like this:

我们正在开发一个应用程序,该应用程序将面向包括英国和美国在内的多个地区的客户。在许多视图页面上,我们显示如下日期:

@Model.EventDate.ToString("dd/MM/yyyy HH:mm")

This has worked well in the UK however now that we are deploying a US version it should be something like (day/month switched around):

这在英国很有效,但是现在我们正在部署一个美国版本,它应该是这样的(日/月转换):

@Model.EventDate.ToString("MM/dd/yyyy HH:mm")

Obviously we don't want to have 2 codebases, 1 for the UK and 1 for the US.

显然我们不希望有两个码基,一个是英国,一个是美国。

Is there anyway we can render dates like this according to the region we are in?

我们可以根据所处的区域来渲染这样的日期吗?

My guess is that the first step would be rendering dates like this:

我的猜测是,第一步是绘制这样的日期:

@Html.DisplayFor(n => Model.EventDate)

Then adding an attribute:

然后添加一个属性:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}" )]

Again the problems seems to be that the format is hardcoded in the attribute.

同样,问题似乎是格式在属性中是硬编码的。

Any ideas?

什么好主意吗?

2 个解决方案

#1


2  

DateTime.ToString method has a version with two arguments:

DateTime。ToString方法的版本有两个参数:

public string ToString(
  string format,
  IFormatProvider provider
)

plus, for the format argument supports formats that produce different results for different cultures - e.g. "d" value:

另外,对于格式参数,支持为不同文化产生不同结果的格式——例如。“d”价值:

date.ToString("d", provider) 

will produce 01.10.2008 for de-DE culture, but 10/1/2008 for en-US.

将于2008年10月10日为en-US公司提供10/1/2008的de-DE文化。

See Examples section of that MSDN article for more.

更多信息请参见MSDN文章的示例部分。

#2


0  

You need to determine a culture string, like en-US, from the incoming request and then map this to a custom format string. You can then create a CultureInfo instance from the culture string. Example:

您需要确定来自传入请求的区域性字符串(如en-US),然后将其映射到自定义格式字符串。然后,您可以从区域性字符串创建一个CultureInfo实例。例子:

new CultureInfo("en-US")

Then using this with the DateTime.ToString method

然后使用DateTime。ToString方法

#1


2  

DateTime.ToString method has a version with two arguments:

DateTime。ToString方法的版本有两个参数:

public string ToString(
  string format,
  IFormatProvider provider
)

plus, for the format argument supports formats that produce different results for different cultures - e.g. "d" value:

另外,对于格式参数,支持为不同文化产生不同结果的格式——例如。“d”价值:

date.ToString("d", provider) 

will produce 01.10.2008 for de-DE culture, but 10/1/2008 for en-US.

将于2008年10月10日为en-US公司提供10/1/2008的de-DE文化。

See Examples section of that MSDN article for more.

更多信息请参见MSDN文章的示例部分。

#2


0  

You need to determine a culture string, like en-US, from the incoming request and then map this to a custom format string. You can then create a CultureInfo instance from the culture string. Example:

您需要确定来自传入请求的区域性字符串(如en-US),然后将其映射到自定义格式字符串。然后,您可以从区域性字符串创建一个CultureInfo实例。例子:

new CultureInfo("en-US")

Then using this with the DateTime.ToString method

然后使用DateTime。ToString方法