Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i assign only year say 2011 in a datetime variable in c#

Tags:

c#

datetime

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.

like image 631
Pankouri Avatar asked Jul 04 '11 11:07

Pankouri


People also ask

How do I only display date from DateTime?

ToString() − One more way to get the date from DateTime is using ToString() extension method. The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch. DateTime. Date − will also remove the time from the DateTime and provides us the Date only.

How do I assign a variable in DateTime?

There are two ways to initialize the DateTime variable: DateTime DT = new DateTime();// this will initialze variable with a date(01/01/0001) and time(00:00:00). DateTime DT = new DateTime(2019,05,09,9,15,0);// this will initialize variable with a specific date(09/05/2019) and time(9:15:00).

How do I convert a DateTime to a specific format?

The ToString() method of the DateTime class is used to convert a DateTime date object to string format. The method takes a date format string that specifies the required string representation.

What is the Z in DateTime?

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).


2 Answers

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.

like image 181
Nico Beemster Avatar answered Oct 04 '22 20:10

Nico Beemster


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

like image 37
Pranay Rana Avatar answered Oct 04 '22 22:10

Pranay Rana