我正在尝试创建一个将1225转换为12/25/13的文本框。在做了大量的研究之后,我认为“DateTime.TryParseExact”是我需要使用的,但是我无法让它工作。这是我的代码:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateValue;
string[] DateTimeFormats = new string[]{
"MM/dd/yy","MM/dd/yy HH:mm","MM/dd/yy HH:mm:ss","HH:mm","HH:mm:ss",
"M/d/yy","M/d/yy HH:mm","M/d/yy HH:mm:ss",
"MM/dd/yyyy","MM/dd/yyyy HH:mm","MM/dd/yyyy HH:mm:ss",
"MMddyy","MMddyyHHmm","MMddyyHHmmss","HHmm","HHmmss",
"MMddyyyy","MMddyyyyHHmm","MMddyyyyHHmmss",
"MMddyy HHmm","MMddyy HHmmss",
"MMddyyyy HHmm","MMddyyyy HHmmss",
"yyyyMMdd","yyyyMMddHHmm","yyyyMMddHHmmss"};
if (DateTime.TryParseExact(TheTextBox.Text, DateTimeFormats, provider, DateTimeStyles.None, out dateValue))
{
TheTextBox.Text = dateValue.ToString("d MMMM yyyy");
}
任何想法如何解决这个问题?
答案 0 :(得分:1)
如果可以预测所有可能的格式,那么你可以试试这样的
static void Main(string[] args)
{
CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;
dateString = "0501";
var dateFormats = new String[] {"MM/dd/yy","MM/dd/yy HH:mm","MM/dd/yy HH:mm:ss","HH:mm","HH:mm:ss",
"M/d/yy","M/d/yy HH:mm","M/d/yy HH:mm:ss",
"MM/dd/yyyy","MM/dd/yyyy HH:mm","MM/dd/yyyy HH:mm:ss",
"MMddyy","MMddyyHHmm","MMddyyHHmmss","HHmm","HHmmss",
"MMddyyyy","MMddyyyyHHmm","MMddyyyyHHmmss",
"MMddyy HHmm","MMddyy HHmmss",
"MMddyyyy HHmm","MMddyyyy HHmmss",
"yyyyMMdd","yyyyMMddHHmm","yyyyMMddHHmmss", "MMdd"};
bool matchFound = false;
foreach (var dateFormat in dateFormats)
{
if (DateTime.TryParseExact(dateString, dateFormat, enUS, DateTimeStyles.None, out dateValue))
{
matchFound = true;
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue.ToString("dd MM yyyy"), dateValue.Kind);
}
}
if (!matchFound)
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
Console.ReadKey();
}
答案 1 :(得分:0)
对于您提供的示例,请考虑对您的代码进行以下更改...
string[] DateTimeFormats = new string[]{"MMdd"};
答案 2 :(得分:0)
您可以使用DateTime.ParseExact
将string
翻译成DateTime
:
textBox1的文本为1225
:
DateTime date = DateTime.ParseExact(textBox1.Text,"MMdd",CultureInfo.InvariantCulture);
string yourDate = date.ToString("MM/dd/yy"));
//yourDate is 12/25/13
注意:这将始终返回当前年份的日期(此处为:2013)。