using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tzkj.Core.System
{
public static class GenerateOrderNo
{
private static object obj = new object();
private static int GuidInt { get { return Guid.NewGuid().GetHashCode(); } }
private static string GuidIntStr { get { return Math.Abs(GuidInt).ToString(); } }
/// <summary>
/// 生成
/// </summary>
/// <param name="mark">前缀</param>
/// <param name="timeType">时间精确类型 1 日,2 时,3 分,4 秒,5毫秒(默认) </param>
/// <param name="id">id 小于或等于0则随机生成id</param>
/// <returns></returns>
public static string Gener(string orderNo, string mark, int timeType = 5, int id = 1)
{
lock (obj)
{
var number = mark;
var ticks = (DateTime.Now.Ticks - GuidInt).ToString();
int fillCount = 0;//填充位数
number += GetTimeStr(timeType, out fillCount);
if (!orderNo.IsNullOrWhiteSpace())
{
var numberNo = orderNo.Substring(25);
if (numberNo.Length > 3)
{
number += $"{ticks.Substring(ticks.Length - (fillCount + 3))}{(long.Parse(numberNo) + 1)}";
}
else
{
int count = numberNo.Count(x => x == '0');
var str = (long.Parse(numberNo) + 1).ToString();
str = str.PadLeft(count == 1 ? count + 2 : count + 1, '0');
number += $"{ticks.Substring(ticks.Length - (fillCount + 3))}{str}";
}
}
else if (id > 0)
{
//number += ticks.Substring(ticks.Length - (fillCount + 3)) + id.ToString().PadLeft(10, '0');
number += $"{ticks.Substring(ticks.Length - (fillCount + 3))}{id.ToString().PadLeft(3, '0')}";
}
else
{
number += ticks.Substring(ticks.Length - (fillCount + 3)) + GuidIntStr.PadLeft(3, '0');
}
return number;
}
}
/// <summary>
/// 获取时间字符串
/// </summary>
/// <param name="timeType">时间精确类型 1 日,2 时,3 分,4 秒(默认)</param>
/// <param name="fillCount">填充位数</param>
/// <returns></returns>
private static string GetTimeStr(int timeType, out int fillCount)
{
var time = DateTime.Now;
if (timeType == 1)
{
fillCount = 6;
return time.ToString("yyyyMMdd");
}
else if (timeType == 2)
{
fillCount = 4;
return time.ToString("yyyyMMddHH");
}
else if (timeType == 3)
{
fillCount = 2;
return time.ToString("yyyyMMddHHmm");
}
else if (timeType == 4)
{
fillCount = 0;
return time.ToString("yyyyMMddHHmmss");
}
else
{
fillCount = 0;
return time.ToString("yyyyMMddHHmmssffff");
}
}
}
}
C# 生成订单号
于 2024-01-04 10:21:25 首次发布