How can I calculate the total time in java?

Hello!
I need to calculate the total time!
For example I have start time:
          Format formatter1;
          Date date1 = new Date();
          formatter1 = new SimpleDateFormat("hh:mm:ss");
          String startTime = formatter1.format(date1);
          //startTime = "14:20:40";
And I have finish time:
          Format formatter2;
          Date date2 = new Date();
          formatter2 = new SimpleDateFormat("hh:mm:ss");
          String finishTime = formatter2.format(date2);
          //finishTime = "08:30:55";
So, after manually calculating, I get total time: "18:10:15"
How can I calculate the total time in java? (Using formatter1 and formatter2 I suppose)
What I need is to print "total 18:10:15"
Thanks!

800512 wrote:
I did the following but, I think something is wrong here:
I defined before: Date date1 = new Date(); Date date2 = new Date();
And it should be exactly 5 seconds between them.
I found delta between date1 and date2:
Format formatter = new SimpleDateFormat("HH:mm:ss");
          long timeInMilliFromStart = date1.getTime() - date2.getTime() ;
          Date date3 = new Date(timeInMilliFromStart);
          String timeInSecFromStart = formatter.format(date3);
and I get always
//timeInSecFromStart = 02:00:05
But it should be exactly 00:00:05.
What can be a problem?Because, like I said, a Date measure an instant in time, not a duration. So when you have 5000 ms, and you turn that into a Date, that means 5 sec. after the epoch, which works out to 1/1/1970 00:00:05.000 GMT.
As I mentioned, if you're not currently in GMT, then you have to set the TZ of the DateFormat to GMT. Right now, it's showing you the time in your TZ. If you included the date in your SimpleDateFormat, you'd see either 1/1/1970 or 12/31/1969, depending on which TZ you're in.
Bottom line: You're trying to use these classes in a way they're not meant for, and while you can get the results you want for a limited set of inputs if you understand what these classes do and how to work with that, it's a brittle approach and comes with all kinds of caveats.

Similar Messages

  • How can I calculate the request time ?

    Hello,
    How can I calculate the total consume time in each request ?
    For example, I want to start calculating the time when I click on a Link or a button and the end time when it completed load the page !
    Eric

    You could use a filter like this one:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.text.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    public class TimeFilter implements Filter {
        // The filter configuration object we are associated with.  If
        // this value is null, this filter instance is not currently
        // configured.
        private FilterConfig filterConfig = null;
        private static final boolean debug = false;
        private long start = 0;
        private long end = 0;
        public TimeFilter() {
        private void doBeforeProcessing(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {
            if (debug) log("CalendarFilter:DoBeforeProcessing");
            System.out.print("In Filter  ");
            this.start = System.currentTimeMillis();
            System.out.println((new java.util.Date()).toString() +
                               " start request ");
        private void doAfterProcessing(ServletRequest request, ServletResponse response)
        throws IOException, ServletException {
            if (debug) log("TimeFilter:DoAfterProcessing");
            System.out.println("Completion Time = " + (System.currentTimeMillis() - start));
         * @param request The servlet request we are processing
         * @param result The servlet response we are creating
         * @param chain The filter chain we are processing
         * @exception IOException if an input/output error occurs
         * @exception ServletException if a servlet error occurs
        public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain)
        throws IOException, ServletException {
            if (debug) log("TimeFilter:doFilter()");
            doBeforeProcessing(request, response);
            Throwable problem = null;
            try {
                chain.doFilter(request, response);
            catch(Throwable t) {
                problem = t;
                t.printStackTrace();
            doAfterProcessing(request, response);
            // If there was a problem, we want to rethrow it if it is
            // a known type, otherwise log it.
            if (problem != null) {
                if (problem instanceof ServletException) throw (ServletException)problem;
                if (problem instanceof IOException) throw (IOException)problem;
                sendProcessingError(problem, response);
         * Return the filter configuration object for this filter.
        public FilterConfig getFilterConfig() {
            return (this.filterConfig);
         * Set the filter configuration object for this filter.
         * @param filterConfig The filter configuration object
        public void setFilterConfig(FilterConfig filterConfig) {
            this.filterConfig = filterConfig;
         * Destroy method for this filter
        public void destroy() {
         * Init method for this filter
        public void init(FilterConfig filterConfig) {
            this.filterConfig = filterConfig;
            if (filterConfig != null) {
                if (debug) {
                    log("TimeFilter:Initializing filter");
         * Return a String representation of this object.
        public String toString() {
            if (filterConfig == null) return ("TimeFilter()");
            StringBuffer sb = new StringBuffer("TimeFilter(");
            sb.append(filterConfig);
            sb.append(")");
            return (sb.toString());
        private void sendProcessingError(Throwable t, ServletResponse response) {
            String stackTrace = getStackTrace(t);
            if(stackTrace != null && !stackTrace.equals("")) {
                try {
                    response.setContentType("text/html");
                    PrintStream ps = new PrintStream(response.getOutputStream());
                    PrintWriter pw = new PrintWriter(ps);
                    pw.print("<html>\n<head>\n</head>\n<body>\n"); //NOI18N
                    // PENDING! Localize this for next official release
                    pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
                    pw.print(stackTrace);
                    pw.print("</pre></body>\n</html>"); //NOI18N
                    pw.close();
                    ps.close();
                    response.getOutputStream().close();;
                catch(Exception ex){ }
            else {
                try {
                    PrintStream ps = new PrintStream(response.getOutputStream());
                    t.printStackTrace(ps);
                    ps.close();
                    response.getOutputStream().close();;
                catch(Exception ex){ }
        public static String getStackTrace(Throwable t) {
            String stackTrace = null;
            try {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                t.printStackTrace(pw);
                pw.close();
                sw.close();
                stackTrace = sw.getBuffer().toString();
            catch(Exception ex) {}
            return stackTrace;
        public void log(String msg) {
            filterConfig.getServletContext().log(msg);
    }and in the web.xml :
       <filter>
            <filter-name>TimeFilter</filter-name>
            <filter-class>
                com.filter.TimeFilter
            </filter>
        <filter-mapping>
            <filter-name>TimeFilter</filter-name>
            <url-pattern>/services/*</url-pattern>
        </filter-mapping > 

  • How can I calculate the total size of my email messages?

    I have an iMac and MacBook Pro. I use Apple's Mail application on each computer and have three email accounts that are feeding into it. I currently synchronize everything through MobileMe. I want to know how to calculate how many MB (probably several GB!) of space my email messages are now using, as I want to upgrade to Lion on the two computers and will soon be getting a 32BG iPad on which I would like to use the Mail application as well. I'd like to know in advance if I need to pay for more than the 5GB of free storage that iCloud will give me before making these changes, as I don't want to lose my email messages. For various reasons, I'd prefer not to go the route of archiving the messages. I can't figure out how to calculate how much space the messages are currently using.

    The important detail is the cylinders not the partition numbers. The partitions are simply slots where cylinder space can be assigned if its available.
    The backup partition (2) represents the whole disk and shows you have 14086 cylinders available.
    But you'll notice that all of those cylinders are already assigned to various partitions. So there is no free space available.

  • How can I calculate the waveform integral in a defined time interval?

    Hi:
    I need your help. How can I calculate the waveform integral in a defined time interval? For example: from "0" to "2pi"?!
    Thanks.

    Hello Clecio,
    You might want to try the Integral x(t) VI.  The documentation for this VI notes:
    Performs the discrete integration of the sampled signal X. Integral x(t) calculates a definite integral. The value of the output array at any value x is the area under the curve of the input array between 0 and x.
    You would pass the samples of the waveform that fall between your particular window, then pass 1/number of samples for the d(t) parameter.
    Hope that helps.
    Wendy L
    LabWindows/CVI Developer Newsletter - ni.com/cvinews

  • How can I get the elapse time for execution of a Query for a session

    Hi ,
    How can I get the elapse time for execution of a Query for a session?
    Example - I have a report based on the procedure ,when the user execute that it takes say 3 min. to return rows.
    Is there any possible way to capture this session info. for this particular execution of query along with it's execution elapse time?
    Thanks in advance.

    Hi
    You can use the dbms_utility.get_time tool (gives binary_integer type value).
    1/ Initialize you time and date of beginning :
    v_beginTime := dbms_utility.get_time ;
    2/ Run you procedure...
    3/ Get end-time with :
    v_endTime := dbms_utility.get_time ;
    4/ Thus, calculate elapsed time by difference :
    v_elapsTime := v_endTime - v_beginTime ;
    This will give you time elapsed in of 100th of seconds...
    Then you can format you result to give correct print time.
    Hope it will help you.
    AL

  • How can i calculate the average in java

    how can i calculate the avergae mark out of two marks for instance in like exam mark out
    of two other ones
    thanks for considering this message

    Average or Mean:
    sum_of_N/N
    Here N is the number of marks.
    sum_of_N is the total sum of n(all marks added together)
    public int average(int[] marks) {
    int sum;
    sum = 0;
    for(int i=0;i < marks.length;i++) {
    sum=marks[i]+sum; // keep adding to the total
    return average = sum/marks.length;
    // warning- using an int here can be a pitfall(we could have a decimal outcome).
    }

  • How do I calculate the total size of selected folders?

    Hello
    My question is:
    How do I calculate the total size of selected folders?
    Thank you

    It does show the aggregate size.
    Command-Option-I opens the Inspector window. (Or open the File menu and hold the Option key. Get Info turns into Show Inspector.) The Inspector is similar to the Get Info window but it shows aggregate info for multiple selections. It is also dynamic — if you change the selection while the Inspector is open, the info changes to reflect the current selection.

  • How can i use the airport time capsule as a external hard drive?

    how can i use the airport time capsule as a external hard drive?

    Why do you recommend not place things like iTunes libraries or photo libraries on the drive? It was what I am looking for...
    I suggest that you ask the experts over in the iPhoto Support Community about their opinions on placing an iPhoto or Aperture library on the Time Capsule....even if you plan to use a wired connection for your Mac and the Time Capsule.
    But, if Terrence Devlin answers, be prepared for a lecture about why you should not ever do this.
    If you place the iTunes library on the Time Capsule, be prepared for iTunes to give you messages about not being able to find the library.
    In addtion, LaPastenague has the answer for you in a nutshell......corruption problems.
    Bottom line....the Time Capsule is for your backups.....not "everyday" files and especially not libraries.

  • How can I get the Date & Time to appear on my final project in iMovie11?

    I am using iMovie 11 and have imported video from a Canon Vixia-HF21 camera. The EXIF data is imported along with the video but when I produce the final product, the date and time do not appear.  How can I get the Date  & Time data to appear on the final product?

    There is a date and time Title you can use. If I recall correctly, it displays date plus hours and minutes, but not seconds.

  • How can i set the date time year to my i pod

    how can i set the date time year to my i pod touch

    Hello Theodora,
    You can do this via your iPod's Settings application.
    B-rock

  • How can I reduce the recording time of the webcam?

    How can I reduce the recording time of the webcam?
    thanks
    Alex

    Keep in mind that Logic also has a limit of 8550 quarter notes. So changing the time signature to 4/8 can get longer recording times. So make sure you change this setting along with the song end. See page 93 in the reference manual.
    MBP 1.83 & MDD 1G DP   Mac OS X (10.4.7)   Logic Pro 7.2.2, Motu 828MkII+828, Firebox LC&XT, Tranzport, Unitor8+(3x)AMT-8's

  • How can i request the actual time code of digital video recorder, i am using RS232 interface for asking actual time code of digital video recording

    how can i request the actual time code of digital video recorder, i am using RS232 interface for asking actual time code of digital video recording

    If you have an RS-232 interface to the digital video recorder, it may be that you can send a command to the video recorder in order to get the time code sent back to your application - you would then read this as a string and then incorporate this data into your program.
    The best source of help will be any documentation you have relating to the serial (RS-232) interface with the digital video recorder. This documentation should have commands that you can send to the recorder and expected response strings that you should get back from the device. This task should be straightforward but can often be frustrating without documentation about the video recorder. This will not be something that you can "guess" - past experience in writing serial communication ap
    plications has shown that a good manual is your best friend.
    Failing this if you have any source code for example programs that have already been written to communicate with the recorder, you might be able to extract the relevant ASCII strings and use them within your application. This is true whether you are using LabVIEW or a text-based language.
    Jeremy

  • How can I change the shipping time from 1-2 weeks to 2 days

    How can I change the shipping time from 1-2 weeks to 2 days. Thank you in advance.

    Right you are, R_Kelly. Thanks, that did the trick. Ukgaurav also pointed out some choices in the Displays and Cursors Preferences with which I fine-tuned the tool cursor appearance.

  • How can I see the total amount of songs in itunes?

    How Can I see the total amount of songs I have in itunes 11.0.1.12?  Totally different from older version.

    From the menu bar, select "View' then "Show Status Bar"

  • How can i get the executing time of a IMAQ function.function could be IMAQ acquire IMAQ acquire.

    how can i get the executing time of a IMAQ function.function could be IMAQ acquire IMAQ acquire.

    Hello,
    This question was answered under a different category, here is the link:
    http://exchange.ni.com/servlet/ProcessRequest?RHIVEID=101&RPAGEID=137&HOID=5065000000050000004EBA0000&HTHREAD=000047694&UCATEGORY_0=_15_&UCATEGORY_S=0
    Regards
    Russell B.
    National Instruments
    Applications Engineering
    Engineering Team Leader
    G Systems, www.gsystems.com
    Certified LabVIEW Architect
    Certified Professional Instructor

Maybe you are looking for