Reputation: 55
How can I parse DateTime variables only year to Integer type?
I would like to parse DateTime variable (2008-06-08) to a integer type variable that would contain only year (2008)
I have tried converting DateTime to string and string parsing to int, but maybe there is a better way to do so?
Upvotes: 0
Views: 9483
Reputation: 460288
If you already have a DateTime
as stated you just need to use the Year
property:
int year = dt.Year;
If you have a string you have to parse it first, f.e. by using ParseExact
:
DateTime dt = DateTime.ParseExact("2008-06-08", "yyyy-MM-dd", CultureInfo.InvariantCulture);
Upvotes: 8