Share via


How To read last two digits from Year

Question

Monday, July 28, 2014 12:30 PM

I want to read last two digits of year if it is %y, %Y for whole Year

So I tried like below...but it is not working...

Can any one Tell How to retrive it...and why this code does not work....Thanks in advance

case "%Y":

sResolvedDateTimePart =

String.Format("{0,4:D4}", DateTime.Now.Year);

case "%y":

sResolvedDateTimePart =

String.Format("{0,2:D2}", DateTime.Now.Year);

All replies (4)

Monday, July 28, 2014 4:35 PM âś…Answered | 1 vote

A slightly more complete example:

int YearsSinceStartOfCentury = DateTime.Now.Year % 100;

http://msdn.microsoft.com/en-us/library/system.datetime.year.aspx

You already got the year as integer. Worst thing you could do is transform it to string first.

%100 (read: "Modulo one-hundred") will give you the rest of a division of Year by 100.

1914 and 2014  %100 would both result in 14.
1900 and 2000 would both result in 0 (division without rest).

If %2 == 0, it is a even number.

Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively.


Monday, July 28, 2014 12:34 PM | 1 vote

Hello,

Something like that:

DateTime mydate = new DateTime(2014, 07, 28); 
string lastTwoDigitsOfYear = mydate .ToString("yy");

Regards

Cedric


Monday, July 28, 2014 2:10 PM

DateTime.Now.Year % 100

Monday, July 28, 2014 4:31 PM | 1 vote

I want to read last two digits of year

So I tried like below...but it is not working...

Can any one Tell ... why this code does not work

sResolvedDateTimePart =String.Format("{0,2:D2}", DateTime.Now.Year);

The precision and alignment specifiers (2 in your example) indicate the *minimum* number of
digits required in the output. They do not specify the *maximum* number of digits. When you
specify 2 you are saying the output should have *at least* 2 digits. But it may have more,
and will have more if the value being formatted is more than 2 digits long. These specifiers
never cause *truncation* of the value being formatted, which is what you appear to have been
expecting.

  • Wayne