P H*_*P H 5 .net c# parsing datetime-format
嗨,我正在尝试解析诸如“1012012”、“2012 年 1 月 1 日”之类的日期字符串。
阅读 Api 它说在日期没有前导 0 的情况下使用 d,%d。不能让它适用于像“1012012”这样的日期
尝试将“d MMM YYYY”用于“2012 年 1 月 1 日”,我用什么来使 'st'、'th' 起作用?
using System;
using System.IO;
using System.Globalization;
namespace test
{
class Script
{
static public void Main(string [] args)
{
//String dateString = "9022011"; // q1
String dateString = "9th February 2011"; //q2
System.DateTime date = DateTime.MinValue;
string[] format = { "ddMMyyyy", "d MMM yyyy" }; // what would be the correct format strings?
if (DateTime.TryParseExact(dateString,format,new CultureInfo("en-AU"),DateTimeStyles.None,out date))
{
Console.Out.WriteLine(date.ToString());
}
else
{
Console.Out.WriteLine("cant convert");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)如果您想解析特定于区域性的日期字符串,您应该使用匹配的区域性。CultureInfo.InvariantCulture这不是一个好主意,因为它只适用于英文字符串。
但是,您想要做的事情仅使用格式说明符是不可能的,因为当天没有可以解析“th”、“st”等字符串的方法。您必须事先手动删除它们。