How to get the current time in seconds in Java?

Posted by Joys of Programming on in Java

Java provides functions like currentTimeMillis and nanoTime to print the current time in milliseconds and nanoseconds respectively. But to get the system time in seconds, we can make use either of these functions.  The following program illustrates this

1 second = 1000 milliseconds = 1000000000 nanoseconds

class CurrentTimeSeconds {
   public static void main(String args[]){
     long time = System.currentTimeMillis()/1000;
     System.out.println("Current Time: "+time+"s");
     time = System.nanoTime()/1000000000L;
     System.out.println("Current Time: "+time+"s");
   }
}

The program generates the following output:

Current Time: 1259590813s
Current Time: 1259590813s

Note: Both these function return the time passed since January 1, 1970.

Reblog this post [with Zemanta]


Tags:

Comments:

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright © 2009-2012 Joys of Programming All rights reserved.
Desk Mess Mirrored v1.8.1 theme from BuyNowShop.com.