javacalendarunix-timestampjava-calendar

Java: Unix time in seconds to milliseconds


I get a 10 digit timestamp from a json file and I've just figured out that this is Unix time in seconds and not in milliseconds.

So I went to my DateUtils class multiplied the timestamp in seconds with 1000, in order to convert it to timestamp in milliseconds.

When I tried to test isToday(), this line of code gave me a year like 50000 something...

int otherYear = this.calendar.get(Calendar.YEAR);

What is the mistake here?

DateUtils.java

public class DateUtils{

 public class DateUtils {
    private Calendar calendar;

    public DateUtils(long timeSeconds){
        long timeMilli = timeSeconds * 1000;
        this.calendar = Calendar.getInstance();
        this.calendar.setTimeInMillis(timeMilli*1000);
    }
    private boolean isToday(){
        Calendar today = Calendar.getInstance();
        today.setTimeInMillis(System.currentTimeMillis());

        // Todays date
        int todayYear = today.get(Calendar.YEAR);
        int todayMonth = today.get(Calendar.MONTH);
        int todayDay = today.get(Calendar.DAY_OF_MONTH);

        // Date to compare with today
        int otherYear = this.calendar.get(Calendar.YEAR);
        int otherMonth = this.calendar.get(Calendar.MONTH);
        int otherDay = this.calendar.get(Calendar.DAY_OF_MONTH);

        if (todayYear==otherYear && todayMonth==otherMonth && todayDay==otherDay){
            return true;
        }
        return false;
    }
}

Solution

  • The problem is in this block of code here:

        long timeMilli = timeSeconds * 1000;
        this.calendar = Calendar.getInstance();
        this.calendar.setTimeInMillis(timeMilli*1000);
    

    You're multiplying the time by 1000 twice; remove one of the * 1000's and you should be good to go :)