繁体   English   中英

转换日期格式代码到目前为止

[英]Convert Date Formatting Codes to date

用户应该以格式输入日期: %m %d %Y

我需要做的是将日期转换为: 11 11 2013 (今天的日期)。 我没有多做日期。 是否有一些方法可以开箱即用? 我浏览了DateTime选项但找不到我需要的东西。

编辑:

从收到的答案来看,似乎不是很清楚我在问什么。

在我们的软件中,用户可以按以下格式插入日期:

http://ellislab.com/expressionengine/user-guide/templates/date_variable_formatting.html

我试图解析此用户输入并返回今天的日期。 所以从上面的链接:

%m - 月 - “01”到“12”

%d - 月中的某天,前导零的2位数 - “01”到“31”

%Y - 年,4位数 - “1999”

我想知道是否有一种方法将%m %d %Y作为输入并以指定的格式返回相应的今天日期(今天是11 11 2013 )。 或者至少接近那个。 希望现在更清楚了。

编辑2:

在进一步挖掘之后,我发现我正在寻找的东西相当于C#中的C ++ strftime。

http://www.cplusplus.com/reference/ctime/strftime/

但由于某些原因,我无法在C#中看到这样的示例。

您可以使用DateTime.TryParseExact将字符串解析为日期,使用DateTime-ToString将其转换回具有所需格式的字符串:

DateTime parsedDate;
if (DateTime.TryParseExact("11 11 2013", "MM dd yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{ 
    // parsed successfully, parsedDate is initialized
    string result = parsedDate.ToString("MM dd yyyy", System.Globalization.CultureInfo.InvariantCulture);
    Console.Write(result);
}

我对DateTime输入和输出的了解:

http://www.dotnetperls.com/datetime-parse用于输入(解析)

http://www.csharp-examples.net/string-format-datetime/用于输出(格式化)

string dateString = "01 01 1992";
string format = "MM dd yyyy";

DateTime dateTime = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);

编辑,因为他的编辑使我的上述答案无关紧要(但将留在那里供参考):

根据您的说法,您希望以动态定义的格式输出今天的日期?

所以,如果我想看月,日,年,我说“MM dd YY”,你就把它还给我了?

如果是这样:

DateTime dt = DateTime.Today; // or initialize it as before, with the parsing (but just a regular DateTime dt = DateTime.Parse() or something quite similar)

然后

String formatString = "MM dd YY";
String.Format("{0:"+ formatString+"}", dt);

不过,你的问题仍然不太清楚。

使用ParseExact

var date = DateTime.ParseExact("9 1 2009", "M d yyyy", CultureInfo.InvariantCulture);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM