Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# convert string to date type

Tags:

c#

asp.net

I've got this string:

string date = "Sun, 17 Mar 2013 12:40:23 +0000";

And trying to convert to a date type but I keep getting a not in correct format error when I try the convert.

DateTime dt = Convert.ToDateTime(date);

And then trying to get it into these formats:

dt.ToString("dd")
dt.ToString("MMMM")
dt.ToString("yyyy")
like image 602
PeteTheGreek Avatar asked Dec 03 '22 00:12

PeteTheGreek


2 Answers

You can use DateTime.ParseExact for the conversion.

Try the following code:

var date = "Sun, 17 Mar 2013 12:40:23 +0000";
var dt = DateTime.ParseExact(date, "ddd, dd MMM yyyy hh:mm:ss zzz", CultureInfo.InvariantCulture);

Console.WriteLine(dt.ToString("dd"));
Console.WriteLine(dt.ToString("MMMM"));
Console.WriteLine(dt.ToString("yyyy"));

Output:

17
March
2013
like image 96
M. Mennan Kara Avatar answered Dec 20 '22 19:12

M. Mennan Kara


Try DateTime.TryParse() or DateTime.Parse()

like image 43
Nefarion Avatar answered Dec 20 '22 19:12

Nefarion