0

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?

1 Answer 1

8

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);
Sign up to request clarification or add additional context in comments.

6 Comments

+1 perfect, OP may also need to consider specific CultureInfo instead of InvariantCulture, but then this is only if needed :) .
I get this error: String was not recognized as a valid DateTime.
@JustinaSeliokaite: when do you get it? You've stated that you have DateTime variables. So you actually don't have DateTime variables but string variables which you want to parse to DateTime(as guessed)? Then show what string you have tried to parse. The code above works in any culture as i'm using InvariantCulture.
my date is DateTime? variable.
@JustinaSeliokaite Does your date string match the Format string? The format of the date in the first parameter must match the format specified in the second. (see msdn article - msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx ) If it's a datetime? (nullable Datetime), is it null?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.