
c#如何如何生成年月跟4位递增的数字
private string GenerateStr()
{
//获取当前序列号,此处我存储在了配置文件中,实际应用中应该写入数据库或者文本文件中
var currentNumber = ConfigurationManager.AppSettings["number"];
if (string.IsNullOrEmpty(currentNumber))//为空,根据当前年月生成一个
{
var yearMonth = DateTime.Now.Date.ToString("yyyyMM");
var number = yearMonth + "0001";
ConfigurationManager.AppSettings["number"] = number;
return number;
}
//不为空的话截取年月部分与当前年月比较
var yearMonthPart = currentNumber.Substring(0, 6);
var dtNow = DateTime.Now.Date.ToString("yyyyMM");
if (!yearMonthPart.Equals(dtNow))//如果年月不相同,重新生成
{
var number = dtNow + "0001";
ConfigurationManager.AppSettings["number"] = number;
return number;
}
//若年月相同,则根据后面四位序列号+1生成新的序列号
var num = currentNumber.Substring(6, currentNumber.Length - 6);
var nextNum = GetIndex(num);
var result = yearMonthPart + nextNum;
ConfigurationManager.AppSettings["number"] = result;
return result;
}
private string GetIndex(string num)
{
var nextNum = "";
for (int i = 0; i < num.Length; i++)
{
if (num[i] != '0')
{
var number = num.Substring(i, num.Length - i);
nextNum = (int.Parse(number) + 1).ToString();
var zeroLength = num.Length - nextNum.Length;
for (int j = 0; j < zeroLength; j++)
{
nextNum = "0" + nextNum;
}
return nextNum;
}
}
return nextNum;
}
测试成功,
private string getdate()
{
string strResult = string.Empty;
string strLast = "2013070234";//最后加入的一条数据
string strDate = DateTime.Now.ToString("yyyyMM");
if (!string.IsNullOrEmpty(strLast))
{
if (strLast.Substring(0, 6) == strDate)
{
string lastNum = "0000" + (int.Parse(strLast.Substring(6).TrimStart('0')) + 1).ToString();
lastNum = lastNum.Substring(lastNum.Length - 4);
strResult = strDate + lastNum;
}
else
{
strResult = strDate + "0001";
}
}
else
{
strResult = strDate + "0001";
}
return strResult;
}
根据你的意思,大概就是这个样子,首先你得取得上一条数据
2、使用配置文件,将当前的2013070001存储起来,要生产数字时,分析配置文件中的字段即可,if......else.....