C# 日期时间字符串格式年份的最后一位数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9803738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DateTime string format last digit of year
提问by Guillaume
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
谢谢
采纳答案by Roy Dictus
You can do that with simple Modulo math:
你可以用简单的模数数学来做到这一点:
int digit = date.Year % 10;
回答by Chris Gessler
Is this what you want?
这是你想要的吗?
DateTime.Now.Year.ToString().Substring(3);
回答by juergen d
DateTime d = DateTime.Now;
int digit = d.Year % 10;
回答by Wim Ombelets
Why would you not use a simple Substring(1,1) on the 2-digit string output?
为什么不在 2 位字符串输出上使用简单的 Substring(1,1) ?
回答by Guffa
No, there is no custom format stringto 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".
有一个自定义格式字符串“y”,但它仍然会返回两位数字,只是不填充零。即 2009 将被格式化为“9”,但 2010 将被格式化为“10”。
You can use an empty string literal to make "y" be the custom format string instead of the standard format string:
您可以使用空字符串文字使“y”成为自定义格式字符串而不是标准格式字符串:
date.ToString("''y");
This will return the two last digits, for example "12", rather than the standard format "March 2012".
这将返回最后两位数字,例如“12”,而不是标准格式“2012 年 3 月”。

