C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Generate Unique Invoice ID Using Timestamp - Java Program

import java.text.SimpleDateFormat;

import java.util.Date;

 

public class InvoiceIDGenerator {

    public static void main(String[] args) {

       

        // Get current date & time

        Date now = new Date();

 

        // Format the timestamp

        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");

 

        // Generate invoice ID

        String invoiceID = "INV-" + formatter.format(now);

 

        // Display

        System.out.println("Generated Unique Invoice ID: " + invoiceID);

    }

}

Output

 
OUTPUT :
Generated Unique Invoice ID: INV-20250112145730987

Explanation

1. Date now = new Date();

  • Creates an object storing the current date and time.
  • Every millisecond is unique → good for invoice IDs.

2. SimpleDateFormat("yyyyMMddHHmmssSSS")

This pattern converts the timestamp into:

Pattern

Meaning

yyyy

Year

MM

Month

dd

Day

HH

Hour (24-hr)

mm

Minutes

ss

Seconds

SSS

Milliseconds

- Ensures no two invoice IDs are the same.

3. invoiceID = "INV-" + formatter.format(now);

  • Prefix "INV-" makes the ID clearly recognizable.
  • Example:
  • INV-20250112145730987

4. Prints result

Displays the unique invoice number.