Introduction
A Flash Sale Countdown Timer is a tool that helps customers track the remaining time until a flash sale begins or ends. It adds urgency to the event and encourages users to make quick decisions. In this tutorial, we will create a countdown timer in Java that will display the remaining time until the flash sale. The goal of this program is to provide an accurate, real-time countdown to the event.
Objective
The objective is to design a Flash Sale Countdown Timer in Java that will help show the remaining time in days, hours, minutes, and seconds, updating in real-time. This is ideal for online retailers and businesses that want to notify users about an upcoming sale.
Code: Flash Sale Countdown Timer in Java
import java.util.Timer;
import java.util.TimerTask;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FlashSaleTimer {
public static void main(String[] args) {
// Set the date and time for the flash sale
String flashSaleDate = "2025/01/05 12:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
try {
Date saleDate = sdf.parse(flashSaleDate);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Get the current date and time
Date currentDate = new Date();
long difference = saleDate.getTime() - currentDate.getTime();
if (difference <= 0) {
System.out.println("Flash Sale has started!");
timer.cancel(); // Stop the timer once the sale has started
} else {
long days = difference / (1000 * 60 * 60 * 24);
long hours = (difference / (1000 * 60 * 60)) % 24;
long minutes = (difference / (1000 * 60)) % 60;
long seconds = (difference / 1000) % 60;
System.out.println(String.format("Time remaining: %d days, %d hours, %d minutes, %d seconds", days, hours, minutes, seconds));
}
}
}, 0, 1000); // Update every second
} catch (Exception e) {
System.out.println("Error: Invalid date format.");
}
}
}
Program Explanation
This Java program creates a countdown timer for a Flash Sale:
- The date and time of the flash sale are set using the
SimpleDateFormatclass to parse the provided date string into aDateobject. - A
Timerobject is used to schedule a task that runs every second. - On each tick, the program calculates the difference between the current time and the flash sale time in milliseconds.
- It then converts the remaining time into days, hours, minutes, and seconds and displays it on the console.
- If the sale has started, the timer stops and prints a message saying “Flash Sale has started!”.
How to Run the Program:
- Open your favorite Java development environment (IDE) such as IntelliJ IDEA, Eclipse, or NetBeans.
- Create a new project or class file and name it
FlashSaleTimer. - Copy the provided code into the class file.
- Run the program.
- The countdown will appear in the console, updating every second until the flash sale starts.

