.net String.Format (format,date) 忽略格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/318056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 10:40:44  来源:igfitidea点击:

String.Format (format,date) is ignoring format

.netdatetime

提问by chris

Not sure what's going on here.

不知道这里发生了什么。

I have a DateTime object, and when I try:

我有一个 DateTime 对象,当我尝试时:

String.Format( "{0:dd/MM/yyyy}", _date)

the value returned is:

返回值是:

"24-05-1967"

What I want is

我想要的是

"24/05/1967"

Can anyone explain why my format string is being ignored?

谁能解释为什么我的格式字符串被忽略了?

A bit more background: This is a web app which started out life as .net 1.1, and I'm in the process of moving it up to 2.0/3.5.

更多背景信息:这是一个网络应用程序,最初是 .net 1.1,我正在将其升级到 2.0/3.5。

Update:

更新:

If I change the format to {0:dd:MM:yyyy}, it returns 24:05:1967 - it's only the / in the format string that gets changed to the - char.

如果我将格式更改为 {0:dd:MM:yyyy},它会返回 24:05:1967 - 只有格式字符串中的 / 被更改为 - 字符。



Resolution:

解析度:

When updating the app to run under 2.0, the asp.net globalization settings were messed up.

在更新应用程序以在 2.0 下运行时,asp.net 全球化设置被搞砸了。

From the web site properties, ASP.NET tab, Edit Configuration, Application Tab - the culture and UI Culture were both set to the first item in the list (af-ZA) for some bizarre reason.

从网站属性中,ASP.NET 选项卡、编辑配置、应用程序选项卡 - 由于某种奇怪的原因,文化和 UI 文化都被设置为列表中的第一项 (af-ZA)。

回答by Carl Serrander

The / is actually the date separator for your specific culture which could be -, in other words, the format string is not ignored but actually used correctly. Look at what CultureInfo is associated with the running thread:

/ 实际上是您的特定文化的日期分隔符,它可能是 - 换句话说,格式字符串不会被忽略,但实际上使用正确。看一下 CultureInfo 与正在运行的线程相关联的内容:

System.Threading.Thread.CurrentThread.CurrentCulture

If you try this:

如果你试试这个:

String.Format(new CultureInfo("en-US"), "{0:dd/MM/yyyy}", DateTime.Now);

You will get the date formatted with / since that is the correct separator for en-US. What you probably should do is use the short date format string and make sure that the thread has the appropriate culture associated, then this would get you what you want and it will work in a globalized application as well:

您将获得格式化为 / 的日期,因为这是 en-US 的正确分隔符。您可能应该做的是使用短日期格式字符串并确保线程具有相关的适当文化,然后这将获得您想要的东西,并且它也可以在全球化的应用程序中工作:

DateTime.Now.ToString("d", Thread.CurrentThread.CurrentCulture);

Hope this helps!

希望这可以帮助!

回答by Oppositional

You likely want to use the ToString()method of your DateTime object to get the string representation you are after. A format string of "dd'/'MM'/'yyyy"will give you the format you described. Note that you need to escape literal characters in the format string using single quotes.

您可能希望使用DateTime 对象的ToString()方法来获取您所追求的字符串表示形式。格式字符串“dd'/'MM'/'yyyy”将为您提供您描述的格式。请注意,您需要使用单引号对格式字符串中的文字字符进行转义。

Example: DateTime.Now.ToString("dd'/'MM'/'yyyy");

例子: DateTime.Now.ToString("dd'/'MM'/'yyyy");

回答by Lasse V. Karlsen

Unless you specify the IFormatProvider (usually a CultureInfo object), it will by default use Thread.CurrentThread.CurrentCulture's date/time formatting, which will give you the changing results.

除非您指定 IFormatProvider(通常是 CultureInfo 对象),否则默认情况下它将使用 Thread.CurrentThread.CurrentCulture 的日期/时间格式,这将为您提供不断变化的结果。

And yes, it will change / but not :.

是的,它会改变 / 但不会改变 :.

The solution in this case is to specify the format provider, like this:

这种情况下的解决方案是指定格式提供程序,如下所示:

String.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", _date)

回答by Pop Catalin

The "/" character is the culture neutral placeholder for the date time separator character which is defined in Regional Settings. So is the ":" character for time.

“/”字符是区域设置中定义的日期时间分隔符的文化中性占位符。时间的“:”字符也是如此。

To embed the "/" literally and not as a placeholder you need to enclose it in single quotation marks '/' in the format string.

要从字面上嵌入“/”而不是作为占位符,您需要将它括在格式字符串中的单引号 '/' 中。

回答by vijay

This will give you your required output

这将为您提供所需的输出

String.Format( "{0:dd/MM/yyyy}", Convert.ToDateTime(_date));

回答by Mike Gledhill

Interesting thread !

有趣的线程!

I have an application which reads in an Excel file, and lets the user export it's data to a .csv file in a user-defined format.

我有一个读取 Excel 文件的应用程序,并让用户以用户定义的格式将其数据导出到 .csv 文件。

I specifically wanted to give the users the ability to export dates to (exactly) a format like yyyy/mm/dd, regardless of their laptop's culture info.

我特别想让用户能够将日期导出为(完全)像 yyyy/mm/dd 这样的格式,而不管他们的笔记本电脑的文化信息如何。

I tried a few of these suggestions, but the only one which did work was Pop Catalin's suggestion, to wrap any / characters with apostrophes:

我尝试了其中的一些建议,但唯一有效的是 Pop Catalin 的建议,即用撇号包裹任何 / 字符:

outputFormat = outputFormat.Replace("/", "'/'");
valueToExport = ImportedDate.ToString(outputFormat);

This seems to be the onlyway to force ToString() to use the exact format string, without trying to do anything Culture specific.

这似乎是强制 ToString() 使用确切格式字符串的唯一方法,而不尝试做任何特定于文化的事情。

Update

更新

I always find it amusing when I answer a StackOverflow question, then hit the same bug a few years later, and stumble across my own answer !

当我回答 StackOverflow 问题时,我总是觉得很有趣,几年后又遇到了同样的错误,并偶然发现了我自己的答案!

As mentioned in lots of these answers, the solution is to wrap forward-slash characters in apostrophes, to force ToString()to ignore the culture settings.

正如许多这些答案中所提到的,解决方案是将正斜杠字符包装在撇号中,以强制ToString()忽略区域性设置。

So, if your Culture settings have a full-stop character as the date separator character (eg "20.07.2015"), then here's what you'd see, when attempting to nicely format the date of Christmas Day, and how you can easily force it to alwaysuse forward-slashes:

因此,如果您的文化设置有一个句号作为日期分隔符(例如“ 20.07.2015”),那么当您尝试很好地格式化圣诞节的日期时,您会看到以下内容,以及如何轻松强制它始终使用正斜杠:

DateTime dtChristmas = new DateTime(2015, 12, 31);

//  This might return "31/12/2015", "31.12.2015", etc, depending on Culture settings
string str1 = dtChristmas.ToString("dd/MM/yyyy");

//  ...but these two statements will both *always* return "31/12/2015"
string str2 = dtChristmas.ToString("dd'/'MM'/'yyyy");
string str3 = dtChristmas.ToString("dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);

回答by Kevin Tighe

That's odd. That formatting works correctly for me. You might want to try _date.ToString("dd/MM/yyyy") instead (though that's just a shot in the dark).

这很奇怪。这种格式对我来说是正确的。您可能想尝试 _date.ToString("dd/MM/yyyy") 代替(尽管这只是黑暗中的一个镜头)。

回答by Arvo

Regional settings (on web server?) have date delimiters set to '-'. In my locale (EE) output would be "24.05.1967" :)

区域设置(在 Web 服务器上?)将日期分隔符设置为“-”。在我的语言环境 (EE) 输出中将是“24.05.1967”:)