Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

currentTimeMillis() to Years, days, and minutes, and backwords. (hard)

Tags:

java

time

I need System.currentTimeMillis() to be converted into 3 variables:

int Years;
int DaysMonths;
int MinutesHours;

What I mean by DayMonths, and MinutesHours is that, let's say for example we have 2 hours. Then MinutesHours should equale 120 (because 2hours = 120 minutes). But once it reaches 24hours, it should be 0 and passe it to DaysMonths. Same thing for the DaysMonths variable.

And I also need to know how to get this thing reversed. Using this 3 variables, I need an other method to get the System.currentTimeMillis() from them.

I'm having hard time to explain this, but I hope you know what I mean. I really hate dealing with time in java. It's not my thing, but I need it really bad for a game project.

like image 540
Reacen Avatar asked Nov 04 '11 18:11

Reacen


2 Answers

Create a Calendar object:

long millis=System.currentTimeMillis();
Calendar c=Calendar.getInstance();
c.setTimeInMillis(millis);

After this you can get the fields from the Calendar object:

int hours=c.get(Calendar.HOUR);
int minutes=c.get(Calendar.MINUTE);

Then:

int MinutesHours=(hours*60)+minutes;

To go back, you can use the set method in Calendar:

Calendar c=Calendar.getInstance();
c.set(Calendar.MINUTE,minutes);
long millis=c.getTimeInMillis();
like image 124
Andres Olarte Avatar answered Oct 20 '22 01:10

Andres Olarte


Please consider using this library.

http://joda-time.sourceforge.net/

It has a lot of usefull date and time manipulating functions which are really simple!

 DateTime dt = new DateTime(2005, 3, 26, 12, 0, 0, 0);
  DateTime plusPeriod = dt.plus(Period.days(1));
  DateTime plusDuration = dt.plus(new Duration(24L*60L*60L*1000L));
like image 31
r0ast3d Avatar answered Oct 20 '22 00:10

r0ast3d