Reputation:
How to convert the below string to DateTime
in C#?
Mon Apr 22 07:56:21 +0000 2013
When i tried the code with
Convert.ToDateTime("Mon Apr 22 07:56:21 +0000 2013")
it is throwing error as
String was not considered as valid DateTime
Upvotes: 2
Views: 1427
Reputation: 2310
Try DateTime.ParseExact
instead.
Example:
CultureInfo provider = CultureInfo.InvariantCulture;
dateString = "Sun 15 Jun 2008 8:30 AM -06:00";
format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);
More examples are available at http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
Upvotes: 4
Reputation: 33
You can use this:
using System;
using System.Globalization;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
CultureInfo cult = CultureInfo.InvariantCulture;
string txt = "Mon Apr 22 07:56:21 +0000 2013";
string format = "ddd MMM dd hh:mm:ss zzz yyyy";
DateTime dt = DateTime.ParseExact(txt, format, cult);
}
}
}
If you run program from country with +06:00, you get time 13:56:21 with same date
Upvotes: 1
Reputation: 63105
string input = "Mon Apr 22 07:56:21 +0000 2013";
string format = "ddd MMM dd HH:mm:ss +ffff yyyy";
DateTime dt;
if(DateTime.TryParseExact(input,format, CultureInfo.InvariantCulture,
DateTimeStyles.None,out dt))
{
// do something with dt
}
Upvotes: 1
Reputation: 5636
You have basically two options for this. DateTime.Parse() and DateTime.ParseExact(). like
DateTime parseexactdt = DateTime.ParseExact("Mon Apr 22 07:56:21 +0000 2013",
"ddd MMM d HH:mm:ss +0000 yyyy",
CultureInfo.InvariantCulture);
Upvotes: 1
Reputation: 223372
Use DateTime.ParseExact
like:
string str = "Mon Apr 22 07:56:21 +0000 2013";
DateTime dt = DateTime.ParseExact(str,
"ddd MMM d HH:mm:ss +0000 yyyy",
CultureInfo.InvariantCulture);
Upvotes: 1