Java – How To Calculate Seconds Since Midnight

Here is a simple method to calculate seconds since midnight for the current time.
There are a few methods to achieve the same result. This is a quick and easy way.

public getSecondsSinceMidnight() {         

    DateFormat dateFormat = new SimpleDateFormat();      
    java.util.Date date = new java.util.Date();

    dateFormat = new SimpleDateFormat(“HH”);
    date = new java.util.Date();
    int hour = Integer.parseInt(dateFormat.format(date));         

    dateFormat = new SimpleDateFormat(“mm”);
    date = new java.util.Date();
    int minute = Integer.parseInt(dateFormat.format(date));

    dateFormat = new SimpleDateFormat(“ss”);
    date = new java.util.Date();
    int second = Integer.parseInt(dateFormat.format(date));   

    int secondsSinceMidnight = (hour* 3600) + (minute * 60) + second;      

    System.out.println(“Current Time:” + hour + “:” + minute + “:” + second);
    System.out.print(“Seconds Since Midnight: ” + secondsSinceMidnight);                       

 }

Amongst other things, seconds since midnight can be used in calculations to establish accurate differences between 2 times.

Advertisements

One thought on “Java – How To Calculate Seconds Since Midnight

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s