Java生成時間戳

時間戳 用來命名文件名

通常使用:System.currentTimeMillis() – 1449565025434
但是會出現重複,同時間多次請求建議不使用這種方法

這種方法生成的是唯一的時間編碼 ,– 12081657054320000
/** 時間格式生成唯一編碼Start **/
/* The FieldPosition. /
private static final FieldPosition HELPER_POSITION = new FieldPosition(0);

/** This Format for format the data to special format. */
private final static Format dateFormat = new SimpleDateFormat("MMddHHmmssS");

/** This Format for format the number to special format. */
private final static NumberFormat numberFormat = new DecimalFormat("0000");

/** This int is the sequence number ,the default value is 0. */
private static int seq = 0;

private static final int MAX = 9999;

/**
 * 時間格式生成序列
 * @return String
 */
public static synchronized String generateSequenceNo() {
    Calendar rightNow = Calendar.getInstance();
    StringBuffer sb = new StringBuffer();
    dateFormat.format(rightNow.getTime(), sb, HELPER_POSITION);
    numberFormat.format(seq, sb, HELPER_POSITION);
    if (seq == MAX) {
        seq = 0;
    } else {
        seq++;
    }
    return sb.toString();
}
/************ 時間格式生成唯一編碼End ************/

用做記錄

發佈了30 篇原創文章 · 獲贊 24 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章