Java Random Date getDateRandomId()

Here you can find the source of getDateRandomId()

Description

return a ID contruct on with the current date : sample : 20101223-4687

License

LGPL

Declaration

public static String getDateRandomId() 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.text.DateFormat;
import java.text.DecimalFormat;

import java.text.NumberFormat;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Locale;

public class Main {
    private static String previousDateId = "";

    /**//from   w  ww . ja v a 2  s . com
      * return a ID contruct on with the current date : sample : 20101223-4687
      * 
      * @return
      */
    public static String getDateRandomId() {
        DateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.US);

        NumberFormat formatter = new DecimalFormat("00000");

        String newDateId;

        do {
            Calendar today = Calendar.getInstance();
            int daySec = today.get(Calendar.HOUR_OF_DAY) * 24 * 60 + today.get(Calendar.MINUTE) * 60
                    + today.get(Calendar.SECOND);
            String currentDate = format.format(today.getTime());
            newDateId = currentDate + '-' + formatter.format(daySec);

            if (newDateId.equals(previousDateId)) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        } while (newDateId.equals(previousDateId));

        previousDateId = newDateId;

        return newDateId;
    }
}

Related

  1. generateRandomDate()
  2. getDateRandom()
  3. getDateRand(Date date)
  4. getDateRand()
  5. getRandomDate(Random ran, boolean idNewID)
  6. getRandomDate()