在c#中将字符串转换为日期(dd / MM / yyyy)格式

时间:2010-08-30 13:00:07

标签: c# date-format

我有一个格式为MM / DD / YYYY

的查询字符串

我在c#中使用它

DateTime d = Request.QueryString["dateTime"].toString();

它给了我很多错误,说明日期时间格式无法识别。如果我手动将浏览器地址栏中的日期时间(查询字符串)更改为dd / mm / yyyy,那么程序运行正常。

我无法更改查询字符串,c#中有没有办法从浏览器中获取它然后转换为dd / mm / yyyy这样的日期?

编辑: 查询字符串:

http://localhost:49543/HM/Admin/ViewDetails.aspx?OrderNo=10&DateCreated=08/30/2010

所以你可以看到datecreated部分是MM / DD / YYYY格式。 我无法从c#中获取它。如果我手动将其更改为30/08/2010,则可以正常工作

7 个答案:

答案 0 :(得分:7)

DateTime d = DateTime.ParseExact(Request.QueryString["dateTime"], "dd/MM/yyyy", CultureInfo.InvariantCulture);

答案 1 :(得分:5)

如何将字符串从请求转换为DateTime

DateTime d = DateTime.ParseExact(Request.QueryString["dateTime"], "dd/MM/yyyy", null);

答案 2 :(得分:2)

DateTime.ParseExact是您寻求的解决方案。 但我建议您使用以下函数验证查询字符串数据:

bool isValidDate(string dtStr) {
    string pattern = @"^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[2][0]\d{2})$)";
    System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(pattern);
    return re.IsMatch(dtStr);
}

编辑1:除了ParseExact,您还可以使用以下内容:

DateTime.Parse(dateString, new System.Globalization.CultureInfo("tr-TR"))

土耳其语日期时间格式为dd / MM / YYYY。

答案 3 :(得分:1)

// Parsing:
DateTime d = DateTime.Parse(Request.QueryString["dateTime"].toString());

// Conversion:
string dString = d.ToWhateverFormatYouWant();

以下是关于格式化日期的一些信息:

http://msdn.microsoft.com/en-us/library/az4se3k1(VS.71).aspx

答案 4 :(得分:1)

DateTime.TryParse可能是一个不错的选择..

答案 5 :(得分:0)

您可以使用:DateTime.Now.ToString("dd/MM/yyyy");

答案 6 :(得分:0)

试试这个应该有效

    DateTime d = 
           DateTime.ParseExact(Request.QueryString["dateTime"], 
           "dd'/'MM'/'yyyy",    
           CultureInfo.InvariantCulture);

我遇到了类似的问题:DateTime Format in C#