/// <summary>
/// 获取一个唯一随机数
/// </summary>
/// <returns></returns>
private string GetRand() {
Random rand = new Random();
return string.Format("{0}{1}",DateTime.Now.Ticks.ToString(), rand.Next(9999).ToString().PadRight(4,'0'));
}
有时候,为了让格式统一,当位数不足时,给予补足。比如:2008-01-01 13:42:05,这其中就对月、日、秒进行了补位。
在 C# 中可以对字符串使用 PadLeft 和 PadRight 进行轻松地补位。
PadLeft(int totalWidth, char paddingChar) //在字符串左边用 paddingChar 补足 totalWidth 长度
PadRight(int totalWidth, char paddingChar) //在字符串右边用 paddingChar 补足 totalWidth 长度
示例:
h = h.PadLeft(2, '0');
注意第二个参数为 char 类型,所以用单引号,也可以用 Convert.ToChar(string value) 把字符串转换成 char 类型。如果字符串长度大于 1,则使用 str.ToCharArray()[index]。