C#Asp.Net中的DateTime转换 [英] DateTime Conversion in C# Asp.Net
本文介绍了C#Asp.Net中的DateTime转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
亲爱的所有人,
在C#中将字符串解析为DateTime时,以下字符串格式发生以下异常.
字符串pstrDepartureDateTime ="2012-03-27T6:30";
假设字符串格式为 yyyy-MM-ddTHH:mm (即)
字符串pstrDepartureDateTime ="2012-03-27T06:30";表示可以进行解析,并且datetime转换可以正常工作.
请提供解决方案.
谢谢,
lenin
Dear All,
while parsing the string as DateTime in C#, the Following Exception Occurred for the Following string format.
string pstrDepartureDateTime = "2012-03-27T6:30";
suppose if the string format is in yyyy-MM-ddTHH:mm (i.e)
string pstrDepartureDateTime = "2012-03-27T06:30"; means parsing and the datetime conversion is working fine.
pls give solution.
Thanks,
lenin
推荐答案
一个选项是将Date字符串转换为标准格式Date字符串,然后使用DateTime.ParseExact方法
One option is to bring the Date string into the standard format Date string and then to use DateTime.ParseExact method
static void Main(string[] args) {
string datePattern = @"(\d{4})-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2})";
string dateString = "2012-3-27T6:30";
Match dateMatch = Regex.Match(dateString, datePattern);
string spacers = "00--T:";
if (dateMatch.Success && dateMatch.Groups.Count==6) {
string formattedDateString = dateMatch.Groups[1].Value;
for (int i = 2; i < dateMatch.Groups.Count; i++) {
formattedDateString += spacers[i] + dateMatch.Groups[i].Value.PadLeft(2, '0');
}
var dt = new DateTime(int.Parse(dateMatch.Groups[1].Value),
int.Parse(dateMatch.Groups[2].Value),
int.Parse(dateMatch.Groups[3].Value),
int.Parse(dateMatch.Groups[4].Value),
int.Parse(dateMatch.Groups[5].Value), 0);
Console.WriteLine(formattedDateString);
Console.Write(dt);
Console.ReadKey();
}
}
您可能还会看到 http://msdn.microsoft.com/en-us/library/5hh873ya.aspx [
You might also look at http://msdn.microsoft.com/en-us/library/5hh873ya.aspx[^]. there is a DateTime.TryParseExact that may be even easier and faster.
不确定问题是什么,但是尝试使用DateTime.TryParse
^ ],如果该值是否是日期时间.
Not sure what the question is, but try using DateTime.TryParse
to ensure[^] if the value is a date time or not.
这篇关于C#Asp.Net中的DateTime转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文