Returns the number of milliseconds from midnight. - Java java.util

Java examples for java.util:Millisecond

Description

Returns the number of milliseconds from midnight.

Demo Code


//package com.java2s;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] argv) throws Exception {
        Calendar calendar = Calendar.getInstance();
        System.out.println(timeOfDay(calendar));
    }/*from ww  w  .  j  a  v  a 2s.co m*/

    /**
     * Returns the number of milliseconds from midnight.
     *
     * @param calendar
     *            the calendar to compute the number of milliseconds for
     * @return the number of milliseconds from midnight
     */
    public static long timeOfDay(Calendar calendar) {
        Calendar midnight = normalizeTimeDown((Calendar) calendar.clone());
        return calendar.getTimeInMillis() - midnight.getTimeInMillis();
    }

    /**
     * Returns the number of milliseconds from midnight.
     *
     * @param date
     *            the datetime object to compute the number of milliseconds for
     * @return the number of milliseconds from midnight
     */
    @Deprecated
    public static long timeOfDay(Date date) {
        Date midnight = normalizeTimeDown((Date) date.clone());
        return date.getTime() - midnight.getTime();
    }

    /**
     * Resets the time in the specified datetime object to 0:00:00.000.
     *
     * @param date
     *            the date to operate on
     * @return the altered datetime object
     */
    @Deprecated
    public static Date normalizeTimeDown(Date date) {
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setTime((date.getTime() / 1000) * 1000);

        return date;
    }

    /**
     * Resets the time in the specified datetime object to 0:00:00.000.
     *
     * @param calendar
     *            the datetime object to operate on
     * @return the altered datetime object
     */
    public static Calendar normalizeTimeDown(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar;
    }
}

Related Tutorials