DateTime string format last digit of year

≡放荡痞女 提交于 2019-12-10 12:56:43

问题


I wonder if there is a better way to get the last digit of a year from a datatime object

var date = DateTime.Now;
string year1 = date.ToString("y"); //NOT OK return Month year (eg March 2012)
char year2 = date.ToString("yy")[1]; //OK return last digit of the year (eg 2)
char year3 = date.ToString("yy").Last(); //OK same as above using linq

Anyone know if an already predifine format exist for retreiving the last digit of the year?

Thanks


回答1:


You can do that with simple Modulo math:

int digit = date.Year % 10;



回答2:


No, there is no custom format string to get the last digit of the year.


There is a custom format string "y", but that will still return two digits, only not zero padded. I.e. 2009 will be formatted as "9", but 2010 will be formatted as "10".

You can use an empty string literal to make "y" be the custom format string instead of the standard format string:

date.ToString("''y");

This will return the two last digits, for example "12", rather than the standard format "March 2012".




回答3:


DateTime d = DateTime.Now;
int digit = d.Year % 10;



回答4:


Is this what you want?

DateTime.Now.Year.ToString().Substring(3);



回答5:


Why would you not use a simple Substring(1,1) on the 2-digit string output?



来源:https://stackoverflow.com/questions/9803738/datetime-string-format-last-digit-of-year

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!