/// <summary> /// 生成日期流水号 /// </summary> public class DateSerialNumberGenerator { private static readonly object Lock = new object(); private static string _nowYear;//系统年份 private static string _nowMonth;//系统月份 /// <summary> /// 获取下一个日期流水号 , 步长=1 /// </summary> /// <param name="thisSNumber">当前流水 - 位长[>=7] - 格式[YYYYMMXXX]</param> /// <param name="minSNumberLength">字串位长,默认=7</param> /// <returns></returns> public static string GetNextSNumber(string thisSNumber = null, int minSNumberLength = 9) { //获取系统时间 _nowYear = DateTime.Now.Year.ToString(); _nowMonth = DateTime.Now.Month.ToString().PadLeft(2, ‘0‘); //为空生成当年/月第一个序列号 if (string.IsNullOrEmpty(thisSNumber) || thisSNumber.Length < minSNumberLength) { return _nowYear + _nowMonth + "1".PadLeft(minSNumberLength - _nowYear.Length - _nowMonth.Length, ‘0‘); } lock (Lock) { //截取参数时间 var year = thisSNumber.Substring(0, 4); var month = thisSNumber.Substring(4, 2); var num = thisSNumber.Substring(6); //跨年判定 if (year.Equals(_nowYear)) { //跨月判定 if (month.Equals(_nowMonth)) { return year + month + GetFormatNum(num, thisSNumber.Length); } return year + _nowMonth + "1".PadLeft(thisSNumber.Length - _nowYear.Length - _nowMonth.Length, ‘0‘); } return _nowYear + _nowMonth + "1".PadLeft(thisSNumber.Length - _nowYear.Length - _nowMonth.Length, ‘0‘); } } /// <summary> /// 位移格式化序列号 /// </summary> /// <param name="num">序列号</param> /// <param name="numberlenght">字串位长</param> /// <returns></returns> private static string GetFormatNum(string num, int numberlenght) { string nowNum = (Convert.ToInt32(num) + 1).ToString(); return nowNum.PadLeft(numberlenght - _nowYear.Length - _nowMonth.Length, ‘0‘); } }
结果:
201807001
原文地址:https://www.cnblogs.com/shiruina/p/9359736.html
时间: 2024-10-10 09:27:29