生成日期流水号帮助类
Posted shiruina
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了生成日期流水号帮助类相关的知识,希望对你有一定的参考价值。
/// <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
以上是关于生成日期流水号帮助类的主要内容,如果未能解决你的问题,请参考以下文章