How can I only assign year 2011 in datetime variable in C #

I have an asp as as text box where the user will fill in only the annual value. For this value, I have a Datetime type in a C # application and a date type column in the database. So I want to convert this txtYear.Text to DateTime. But he will hold and / or show the year. Please help me in this situation.

+7
source share
7 answers

A DateTime object will always contain the full DateTime value; you cannot use it to store only a year. (what use will it be anyway?) Also, the year data type is an int, not a DateTime.

So, I would suggest changing your property to datatype int, both in your code and in the database.

+7
source

To display only 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); 
+5
source

You must specify the format of the used DateTime value:

 String dateTimeFormat = "yyyy"; 

To show only part of the DateTime value, use the following:

 dateTimeValue.ToString(dateTimeFormat); 

To read the String value that represents the year in DateTime , use the following:

 DateTime.ParseExact(stringValue, dateTimeFormat, CultureInfo.InvariantCulture); 

The DateTime.ParseExact (String, String, IFormatProvider) method converts the specified string representation of the date and time into its DateTime equivalent using the specified format and format information for a specific culture. The format of the string representation must exactly match the specified format.

The DateTime.ToString method converts the value of the current DateTime object to its equivalent string representation.

+4
source

A DateTime always has a full date component. When you create an instance of DateTime, you need to set the month and day, but you can ignore them in your use.

 DateTime d = new DateTime(int.Parse(txtYear.Text, 1, 1); txtYear.Text = d.ToString("yyyy"); 

Even better is not to use DateTime, but just to use int. If you only have a year, you only need int.

+2
source

Instead of using any string manipulation function, use the Year property. Check the msdn documentation by visiting the link below.

DateTime.Year Property

+1
source

I assume the text field name is txYear

 DateTime dt = new DateTime (Convert.ToInt32(txYear.text),1,1) 

save this dt value in the database

+1
source

If you want only a year, why don't you make it type smallint ?

Anyway, if you really want to do this year,

 DateTime x = new DateTime(Convert.ToInt32(txtYear.text), 1, 1); 

But make sure you confirm that txtYear.text really has a year.

0
source

All Articles