How can I convert a string into datetime in .NET?

前端 未结 2 749
花落未央
花落未央 2020-12-07 04:33

How can I convert dates like \"Jun 17 2009, 03:37 pm ET\" into a DateTime variable using C#?

I have tried DateTime.ParseExact but I haven\'

相关标签:
2条回答
  • 2020-12-07 04:55

    Have you tried DateTime.Parse()? I ususally find that it is not necessary to specify the format unless there is some abiguity between what number is the month and what number is the day.

    0 讨论(0)
  • 2020-12-07 04:59
     // String to DateTime
     String MyString;
     MyString = "1999-09-01 21:34 PM";
     //MyString = "1999-09-01 21:34 p.m.";  //Depends on your regional settings
    
     DateTime MyDateTime;
     MyDateTime = new DateTime();
     MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt", null);
    

    Source: http://www.codeproject.com/KB/cs/String2DateTime.aspx

    Modified to fit your date format:

     // String to DateTime
     String MyString;
     MyString = "Jun 17 2009, 03:37 pm";
    
     DateTime MyDateTime;
     MyDateTime = new DateTime();
     MyDateTime = DateTime.ParseExact(MyString, "MMM dd YYYY, HH:mm tt", null);
    
    0 讨论(0)
提交回复
热议问题