SoFunction
Updated on 2025-03-05

golang The operation of generating order numbers

Year (2 digits) + Day of the year (3 digits) + Random number of specified digits

//Generate a single number//06123xxxxx
//sum at least 10 digits, sum represents the number of all unit numbersfunc MakeYearDaysRand(sum int) string {
  //Year  strs := ().Format("06")
  //What day of the year  days := (GetDaysInYearByThisYear())
  count := len(days)
  if count < 3 {
    //Repeat character 0    days = ("0", 3-count) + days
  }
  //combination  strs += days
  //Remaining random number  sum = sum - 5
  if sum < 1 {
    sum = 5
  }
  // Random number of 0~999999999  ran := GetRand()
  pow := (10, float64(sum)) - 1
  //("sum=>", sum)
  //("pow=>", pow)
  result := ((int(pow)))
  count = len(result)
  //("result=>", result)
  if count < sum {
    //Repeat character 0    result = ("0", sum-count) + result
  }
  //combination  strs += result
  return strs
}
//What day of the yearfunc GetDaysInYearByThisYear() int {
  now := ()
  total := 0
  arr := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
  y, month, d := ()
  m := int(month)
  for i := 0; i < m-1; i++ {
    total = total + arr[i]
  }
  if (y%400 == 0 || (y%4 == 0 && y%100 != 0)) && m > 2 {
    total = total + d + 1
  } else {
    total = total + d
  }
  return total;
}

Supplement: Supporting high concurrent order number generation function based on GO language implementation

1. Fixed 24-bit length order number, milliseconds + process id + serial number.

2. As long as there are no more than 10,000 concurrent times within the same millisecond, the order number will not be repeated.

Github address:/w3liu/go-common/blob/master/number/ordernum/

package ordernum 
import (
  "fmt"
  "/w3liu/go-common/constant/timeformat"
  "os"
  "sync/atomic"
  "time"
)
 
var num int64 
// Generate 24-digit order number//The first 17 digits represent the time accurate to milliseconds, the middle 3 digits represent the process id, and the last 4 digits represent the sequence numberfunc Generate(t ) string {
  s := ()
  m := ()/1e6 - ()/1e9*1e3
  ms := sup(m, 3)
  p := () % 1000
  ps := sup(int64(p), 3)
  i := atomic.AddInt64(&num, 1)
  r := i % 10000
  rs := sup(r, 4)
  n := ("%s%s%s%s", s, ms, ps, rs)
  return n
}
 
//Add 0 before the number with length less than nfunc sup(i int64, n int) string {
  m := ("%d", i)
  for len(m) < n {
   m = ("0%s", m)
  }
  return m
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.