Generation ID template: year, month, day, hour, minute, and second + 6-digit auto-increment code

Source: Internet
Author: User

Generation ID template: year, month, day, hour, minute, and second + 6-digit auto-increment code

Because the order ID, product ID, or any ID is generated, and you do not want to use auto-increment, and are afraid of repetition, you can use the year and day minute and second + 6-digit auto-increment codes (a total of 20 characters) as the ID

 

NOTE: If your ID is of the Long type, you must note that the maximum length of Long is 19 BITs. If you want to convert it directly, you are advised to change it to year, month, day, hour, minute, second, + 5-bit random number.

 

Code:

 

Private static int sequence = 0; private static int length = 6;/*** YYYYMMDDHHMMSS + 6-bit self-growth code (20-bit) * @ author shijing * June 29, 2015 1:25:23 * @ return */public static synchronized String getLocalTrmSeqNum () {sequence = sequence> = 999999? 1: sequence + 1; String datetime = new SimpleDateFormat (yyyyMMddHHmmss ). format (new Date (); String s = Integer. toString (sequence); return datetime + addLeftZero (s, length );} /*** left fill in 0 * @ author shijing * June 29, 2015 1:24:32 * @ param s * @ param length * @ return */public static String addLeftZero (String s, int length) {// StringBuilder sb = new StringBuilder (); int old = s. length (); if (length> old) {char [] c = new char [length]; char [] x = s. toCharArray (); if (x. length> length) {throw new IllegalArgumentException (Numeric value is larger than intended length: + s + LEN + length);} int lim = c. length-x. length; for (int I = 0; I <lim; I ++) {c [I] = '0';} System. arraycopy (x, 0, c, lim, x. length); return new String (c);} return s. substring (0, length );}

 

The test result is as follows:

2015070816503700001


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.