JSON在线解析

提问人:SOJSON用户 提问日期:2017-04-12 09:41 热度:4596
问题标签 Java

要求:用Java生成一个20位的时间格式开头的20位数字的订单号,而且不能重复。


2条回答 我来回答
soゝso| 2017-04-12 09:42

最后输出:

时间17位:20170412094213319
订单号20位:20170412094213319855

soゝso| 2017-04-12 09:42

生成的数值理论上都会重复,只是有一个界限值。

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
 * 
 * 开发公司:SOJSON在线工具 <p>
 * 版权所有:© www.sojson.com
 * 博客地址:http://www.sojson.com/blog/
 * <p>
 * 
 * Demo
 * 
 * <p>
 * 
 * 区分 责任人 日期    说明<br/>
 * 创建 周柏成 2017年4月11日 09:43  <br/>
 *
 * @author zhou-baicheng
 * @email  so@sojson.com
 * @version 1.0,2017年4月11日 09:43 <br/>
 * 
 */
public class Demo {

	public static void main(String[] args) {
		//格式化当前时间
		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String strDate = sfDate.format(new Date());
		//得到17位时间如:20170411094039080
		System.out.println("时间17位:" + strDate);
		//为了防止高并发重复,再获取3个随机数
		String random = getRandom620(3);
		
		//最后得到20位订单编号。
		System.out.println("订单号20位:" + strDate + random);
		
	}
	/**
	 * 获取6-10 的随机位数数字
	 * @param length	想要生成的长度
	 * @return result
	 */
	public static String getRandom620(Integer length) {
		String result = "";
		Random rand = new Random();
		int n = 20;
		if (null != length && length > 0) {
			n = length;
		}
		int randInt = 0;
		for (int i = 0; i < n; i++) {
			randInt = rand.nextInt(10);

			result += randInt;
		}
		return result;
	}
}