C# 将任何字符串格式化为字符串“yyyy/MM/dd”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9806967/
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-08-09 10:41:22  来源:igfitidea点击:

Formatting any string to string "yyyy/MM/dd"

c#stringformatting

提问by Vinicius Ottoni

I have many strings like "20120117" and "20120321". I need to convert it in a new string with this format: "2012/01/17" and "2012/03/21". So, there is a way to do this?

我有很多字符串,比如“20120117”和“20120321”。我需要将其转换为具有以下格式的新字符串:“2012/01/17”和“2012/03/21”。那么,有没有办法做到这一点?

I try:

我尝试:

string dateString = string.format("{0:d", "20120321");

and

string dateString = string.format("{0:yyyy/MM/dd", "20120321"); 

and

string dateString = int.Parse("20120321").ToString("yyyy/MM/dd");

I all cases i don't reach my goal. =/

我在所有情况下都没有达到我的目标。=/

So, i can i do this?

那么,我可以这样做吗?

OBS: There is a way to do that without parse to datetime?

OBS:有没有解析到日期时间的方法?

采纳答案by Shimrod

You have to parse those values in DateTimeobjects first.

您必须首先解析DateTime对象中的这些值。

Example :

例子 :

DateTime dt = DateTime.ParseExact("20120321", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
var result = dt.ToString("yyyy/MM/dd");


Edit after your comments on other answers: if you don't like parsing because it may throw excepations, you can always use TryParse, like this:

在您对其他答案发表评论后进行编辑:如果您不喜欢解析,因为它可能会引发异常,您可以随时使用TryParse,如下所示:

DateTime dt;
bool success = DateTime.TryParseExact("20120321", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
if (success)
{
    var result = dt.ToString("yyyy/MM/dd");
}


Edit 2: Using TryParseExactwith multiple formats:

编辑 2:使用TryParseExact多种格式:

DateTime dt;
string[] formats = { "yyyyMMdd", "yyyy" };

bool success = DateTime.TryParseExact("20120321", formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt);
if (success)
{
    var result = dt.ToString("yyyy/MM/dd");
    Console.WriteLine(result);
}

It will produce 2012/03/21when using "20120321" as input value, and 2012/01/01when using 2012as input value.

2012/03/21当使用“20120321”作为输入值时,2012/01/012012作为输入值使用时,它会产生 。

回答by Austin Salonen

DateTime.ParseExact("20120321", "yyyyMMdd", CultureInfo.CurrentCulture).ToString("yyyy/MM/dd")

You could parse the string but this method gives you validation without any extra code. Imagine receiving "20120230", "20110229", or any other invalid date.

您可以解析字符串,但此方法无需任何额外代码即可为您提供验证。想象一下收到“20120230”、“20110229”或任何其他无效日期。

回答by Simon

Use DateTime.ParseExact to convert to a DateTime, then use ToString on that instance to format as you desire.

使用 DateTime.ParseExact 转换为 DateTime,然后在该实例上使用 ToString 以根据需要进行格式化。

DateTime.ParseExact(dateString, "yyyyMMdd").ToString("yyyy/MM/dd");

EDIT: using Insert: EDIT2: Fixed bugs :-)

编辑:使用插入:EDIT2:修复错误:-)

var newString = dateString.Insert(4, "/").Insert(7, "/");

回答by Jon Skeet

From your comments:

从你的评论:

There is a way to do that without parse to datetime?

有没有解析到日期时间的方法来做到这一点?

Yes, absolutely. If you reallywant to propagate bad data through your system rather than highlighting that it's incorrect, you could definitely use:

是的,一点没错。如果你真的想通过你的系统传播坏数据而不是强调它是不正确的,你绝对可以使用:

// Make sure we'll always be able to get a result whatever the input.
string paddedInput = input + "????????";
string mightBeBadWhoKnows = string.Format("{0}/{1}/{2}",
    paddedInput.Substring(0, 4), // The year, if we're lucky
    paddedInput.Substring(4, 2), // The month, if we're lucky
    paddedInput.Substring(6, 2)); // The day, if we're lucky

But why wouldn'tyou want to spot the bad data?

但是,为什么想要发现坏的数据?

You absolutely shouldparse the data. If you want to be able to continue after receiving bad data having taken appropriate action, use DateTime.TryParseExact. If you're happy for an exception to be thrown, use DateTime.ParseExact. I'd suggest using the invariant culture for both parsing and formatting, unless you really want a culture-sensitive output.

你绝对应该解析数据。如果您希望在收到错误数据并采取适当措施后能够继续,请使用DateTime.TryParseExact. 如果您对抛出异常感到高兴,请使用DateTime.ParseExact. 我建议使用不变文化进行解析和格式化,除非您真的想要一个文化敏感的输出。

回答by Guffa

Just use string operations to insert the slashes:

只需使用字符串操作插入斜杠:

string input = "20120321";

string dateString =
  input.Substring(0, 4) + "/" +
  input.Substring(4, 2) + "/" +
  input.Substring(6);

or

或者

string dateString = input.Insert(6, "/").Insert(4, "/");

回答by Adrian Iftode

If your data is always in the same format and if you don't need to validate it, you can use the following snippet to avoid parsing it with DateTime

如果您的数据始终采用相同的格式,并且您不需要对其进行验证,则可以使用以下代码段来避免使用 DateTime 对其进行解析

var strWithInsert =  input.Insert(4,"/").Insert(7,"/");

回答by Botz3000

If it's a date, try this:

如果是约会,试试这个:

DateTime.ParseExact("20120321","yyyyMMdd", null).ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)

回答by daryal

try this;

尝试这个;

string dateString = DateTime.ParseExact("20120321", "yyyyMMdd",
                              null).ToShortDateString();