how can i assign only year say 2011 in a datetime variable in c#
I have a asp Text box开发者_运维技巧 as where the user will fill only a year value, For this value I have Datetime type Property in c# application and Date type column in DB. So I want to convert that txtYear.Text to DateTime But it will only hold and/or show the year. Please help me in this situation.
A DateTime object will always hold a complete DateTime value, you can't use it to store a year only. (what use would that be anyway?) Besides, the datatype of a "year" is int, not DateTime.
So, I'd like to suggest changing your property to datatype int, both in your code and database.
To display just the year use the format "yyyy".
string s = "2011";
DateTime d = new DateTime(int.Parse(s), 1, 1);
Console.WriteLine(d.ToString("yyyy"));
Console.WriteLine(d);
You have to specify the format of the DateTime
value you are manipulating:
String dateTimeFormat = "yyyy";
To show only a part of the DateTime
value use the following:
dateTimeValue.ToString(dateTimeFormat);
To read a String
value that represents a year into a DateTime
use the following:
DateTime.ParseExact(stringValue, dateTimeFormat, CultureInfo.InvariantCulture);
DateTime.ParseExact Method (String, String, IFormatProvider) converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
DateTime.ToString Method converts the value of the current DateTime object to its equivalent string representation.
Rather than applying any string manipulating function make use of Year property. Check the documentation on the msdn by visiting below link.
DateTime.Year Property
A DateTime always has a full date component. When you create the DateTime instance, you'll need to assign a month and day, but you can ignore them in your usage.
DateTime d = new DateTime(int.Parse(txtYear.Text, 1, 1);
txtYear.Text = d.ToString("yyyy");
Even better would be not to use a DateTime but just use int. If you have only a year, you only need an int.
i assume the text box name is txYear
DateTime dt = new DateTime (Convert.ToInt32(txYear.text),1,1)
save this dt value in database
If you want only the year, why don't you make it of type smallint
?
Anyway if you do really want to make it an year,
DateTime x = new DateTime(Convert.ToInt32(txtYear.text), 1, 1);
But make sure you validate that txtYear.text
actually does have a valid year.
That is how I did and it worked.
string format = "yyyy";
var CurrentYear = DateTime.Now.ToString(format);
精彩评论