2

I have recently started learning java for creating android apps. I have spent hours and hours looking for the right code to be able to use the current time and date as an int. I'm sure it's very easy but I can't seem to find the correct coding. My first app im creating it will be crucial for a number to increase with time. Thank you for your help!

Chris

Cgramme
  • 35
  • 5

2 Answers2

1

You can use it as a long, see javadocs:

But why would you do it, that's another question... Choose wisely :) Nothing wrong with having dates represented as numbers per se, but any calculations are bound to hit some of the numerous corner cases - you might want to look at this SOq for one really mind-boggling examples:

and this SOq for a bunch of best practices:

If you are interested in any date calculations, you may want to look at Joda Time library:

I'd say that when you have such good and well tested libraries readily available, it's rarely a good idea to go your own way.

Community
  • 1
  • 1
icyrock.com
  • 27,952
  • 4
  • 66
  • 85
  • I am honestly VERY new to the java language... Creating this app is my way of learning the language. I'm creating an app for cars and I need to be able to update the entered odometer reading by the average set miles driven. I don't want to ask really how to do everything unless there might be a simple answer to my question. Thank you for the fast response! – Cgramme Mar 01 '12 at 04:02
  • 1
    Sure thing - `getTime` method on a date object will get you what you want - to quote the docs: "Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.". – icyrock.com Mar 01 '12 at 04:20
  • So far I have been able to find tutorials to help me learn all the information I need, alot of "youtube" and "TheNewBoston" I guess I am concerned that I learn it the simplest way and the right way. And by new to the java language I have been studying it for only 3 months now on my own time as a hobby. – Cgramme Mar 01 '12 at 04:27
  • Actually one of the easiest is to get System.getCurrentTimeinMillis() if you don't mind getting the time as a long. You can then always pass that to either java.util.Date or java.util.GregorianCalendar as needed. – Chris Aldrich Mar 01 '12 at 20:04
0

Try to avoid the Date class and use GregorianCalendar instead. It has built-in arithmetic functions, and if you really need it, there's a getTimeInMillis() method.

David Ehrmann
  • 7,366
  • 2
  • 31
  • 40