Search code examples
javalong-integercountdown

Christmas Countdown Off


I am trying to make a Christmas countdown in java however I cannot seem to figure out why the hours are off. This is outputting about 12 hours off from the actual time.

Here is my code:

long now = System.currentTimeMillis();
long christmas = 1387929600000L;
long untilChristmas = christmas - now;

DateFormat df = new SimpleDateFormat("dd-kk-mm-ss");
Date date = new Date(untilChristmas);

System.out.println(df.format(date));

Solution

  • You shouldn't hardcode the date, you should use a Calendar to calculate it:

        long now = System.currentTimeMillis();
        Calendar christmas = Calendar.getInstance();
        christmas.set(Calendar.MONTH, Calendar.DECEMBER);
        christmas.set(Calendar.DAY_OF_MONTH, 25);
        long untilChristmas = christmas.getTimeInMillis() - now;
    
        DateFormat df = new SimpleDateFormat("dd-kk-mm-ss");
        Date date = new Date(untilChristmas);
    
        System.out.println(df.format(date));