Is there any way to create a short unique code like short GUID?

前端 未结 5 1928
予麋鹿
予麋鹿 2021-02-05 03:21

I want to create a short GUID. Is there any way to create a short unique code like short GUID? I want to create a ticket tracking number.

5条回答
  •  执念已碎
    2021-02-05 04:12

    unique within one year, visibly 'random'

    string UniqueID()
    {
        var t = DateTime.UtcNow;
        long dgit = t.Millisecond   * 1000000000L +
                    t.DayOfYear     * 1000000L +
                    t.Hour          * 10000L +
                    t.Minute        * 100L +
                    t.Second;
        return Convert.ToBase64String(BitConverter.GetBytes(dgit).Take(5).ToArray()).TrimEnd('=');
    }
    

    here's one with a customizable character set

    string UniqueID(string CharList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    {
        var t = DateTime.UtcNow;
        char[] charArray = CharList.ToCharArray();
        var result = new Stack();
    
        var length = charArray.Length;
    
        long dgit = 1000000000000L +
                    t.Millisecond   * 1000000000L +
                    t.DayOfYear     * 1000000L +
                    t.Hour          * 10000L +
                    t.Minute        * 100L +
                    t.Second;
    
        while (dgit != 0)
        {
            result.Push(charArray[dgit % length]);
            dgit /= length;
        }
        return new string(result.ToArray());
    }
    

提交回复
热议问题