1. 程式人生 > >生成ID模板:年月日時分秒+6位自增碼

生成ID模板:年月日時分秒+6位自增碼

urn illegal pos cep string builder pop array 結果

因為生成訂單ID、商品ID 或者什麽什麽ID的,不想用自增,又怕反復,於是就用 年與日時分秒 + 6位自增碼 (共計20位長度)來當作ID


註意:假設你的ID是Long型。就要註意,Long的最大長度為19位,假設直接轉的話會有問題,建議改為年月日時分秒+5位隨機數


詳細代碼:

private static int sequence = 0;
	
	private static int length = 6;
	
	/**
	 * YYYYMMDDHHMMSS+6位自增長碼(20位)
	 * @author shijing
	 * 2015年6月29日下午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);
	}
	
	/**
	 * 左填0
	 * @author shijing
	 * 2015年6月29日下午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);

	}

以下是測試的結果:

2015070816503700001



生成ID模板:年月日時分秒+6位自增碼