• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to get "HH:mm:ss" from a long ?

 
author
Posts: 194
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all,
I have a long value that holds how many seconds
the user is connected. I'd like to transalate in
the HH:mm:ss format. The problem is that the "HH"
fields starts with "01" instead of "00" !!

Let me explain better:
------------------------------------------------------------------
long time = 24000; // 24 seconds.

java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("HH:mm:ss");

System.out.println("Time elapsed: " + sdf.format(new java.sql.Date(time)));
------------------------------------------------------------------
Instead of getting 00:00:24, I have 01:00:24 !
How can I get the hours starting from "00" ?
Thanks a lot
Francesco
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Better go back and read the API again. That Date constructor wants time in milliseconds since the beginning of the UNIX era - Jan 1, 1970. It has nothing to do with elapsed time.
You would be better off doing the divisions and modulos to convert your elapsed time to hours, minutes and seconds and then formatting the string.
Bill
 
Ranch Hand
Posts: 823
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you only want whole seconds it might be more painless to do the following:

You don't need to use SimpleDateFormat directly as the format you're using is not a special case.

The above approach is more "Java" than Bill's suggestion but almost certainly less efficient if performance is a factor.

Jules
 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Try this,
let us suppose that the long object holding the no. of milliseconds is date1.

java.util.Date dateObject1 = new java.util.Date(date1);
System.out.println("Time is: " + dateObject1.getHours() + ":" + dateObject1.getMinutes() + ":" + dateObject1.getSeconds());
 
reply
    Bookmark Topic Watch Topic
  • New Topic