最近看到了如下的代码,目的是为了格式化日期和数字:
DateTime tmpTime = clientTime.Subtract(timeLiness);
string hour = (tmpTime.Hour.ToString().Length == 1 ?"0" + tmpTime.Hour : tmpTime.Hour.ToString());
string minute = (tmpTime.Minute.ToString().Length == 1
?"0" + tmpTime.Minute
: tmpTime.Minute.ToString());
string second = (tmpTime.Second.ToString().Length == 1
?"0" + tmpTime.Second
: tmpTime.Second.ToString());
string millSecond = DateTime.Now.ToFileTime().ToString();
if (millSecond.Length == 1)
millSecond +="00";
if (millSecond.Length == 2)
millSecond +="0";
string fileName = string.Format("{0}_BatchInventory_{1}{2}{3}_{4}_{5}_{6}_{7}.{8}",
CPApplication.Current.SellerID, tmpTime.Year,
tmpTime.Month, tmpTime.Day, hour, minute, second, millSecond, fileType);
感觉可能有同学对格式化字符串还不熟悉。这样写很累的。
就这个案例而言,最简单的写法如下:
DateTime tmpTime = clientTime.Subtract(timeLiness);
string fileName = string.Format("{0}_BatchInventory_{1:yyyyMMdd_HH_mm_ss_fff}.{2}",
CPApplication.Current.SellerID, tmpTime, fileType);
这个案例中,格式化数字的写法如下:
DateTime tmpTime = clientTime.Subtract(timeLiness);
string hour = tmpTime.Hour.ToString("00");
string millSecond = DateTime.Now.ToFileTime().ToString("000");
参考资料:
完整的格式化字符串的资料如下:
http://msdn.microsoft.com/zh-cn/library/26etazsy%28v=vs.80%29.aspx