Connect with Expertise | Find Experts, Get Answers, Share Insights

how to Convert String into DateTime

 
Join Date: Nov 2009
Location: Pakistan
Posts: 2
#1: Jan 14 '10
i have to convert only year( such as 2009) into DateTime
i use following method but it returns
(String was not recognized as a valid DateTime.)


string yr = datetimepicker1.Value.Year.ToString();
DateTime dt = System.Convert.ToDateTime(yr);


give me some example plz.

 
Join Date: Apr 2009
Location: Delhi, India
Posts: 91
#2: Jan 14 '10

re: how to Convert String into DateTime


Please write your codes in [code] tags

A DateTime object cannot contain just a year, if you just wanna store a year, then you can probably just use a int variable to do that, and if (not recommended) you want to store only year in DateTime object do something like..

Expand|Select|Wrap|Line Numbers
  1. DateTime dt = new DateTime(datetimepicker1.Value.Year, 1,1);
this will although put month and date as 1st January
 
Join Date: Nov 2009
Location: Pakistan
Posts: 2
#3: Jan 15 '10

re: how to Convert String into DateTime


thnx budddy it works
Frinavale's Avatar
E
M
C
 
Join Date: Oct 2006
Location: The Great White North
Posts: 6,866
#4: Jan 15 '10

re: how to Convert String into DateTime


Hmm I think I would have suggested that you use the DateTime.Parse Method or the DateTime.TryParse Method as apposed to using the DateTime constructor to create a new DateTime object, supplying the first day and month of the year....

The DateTime.Parse(String) method tries to convert the string representation of a date and time value to its DateTime equivalent.

-Frinny
 
Join Date: Apr 2009
Location: Delhi, India
Posts: 91
#5: Jan 15 '10

re: how to Convert String into DateTime


DateTime.Parse wont work either because he was giving just a year...
Reply