Keeping Track of Time (24 Hour System)

I’m creating a game that needs to keep track of time. I have a Time class which has a few methods – constructor, update(), getDay(), getHour() and getMinute(). My Time class also has a speed variable which determines how fast minutes and hours pass. I would know how to implement day counting once I know how to actually keep track of time in hours and minutes. I want to create a time system like The Sims franchise did. How would I go about this? Could someone point me in the right direction?

Thank you in advance!

EDIT #1 - Added Time class
I don’t know why formatting is messed up, but whatever.

package com.bravesites.ivanvinski.game;

public class Time{
    public static final float SPEED_NORMAL = 1f;
    public static final float SPEED_FASTER = 5f;
    public static final float SPEED_FAST = 10f;
    public static final float SPEED_EXTREME = 20f;
    
    private float speed;
    private int hours, minutes;
    
    private int daysPassed;
    private int dayIndex;
    
    public Time(){
	this(SPEED_NORMAL, 12, 0);
    }
    
    public Time(float speed, int hours, int minutes){
	setSpeed(speed);
	this.hours = hours;
	this.minutes = minutes;
    }
    
    public void update(float delta){
	if(minutes >= 60){
	    hours++;
	    minutes = 0;
	}
	
	if(hours > 24){
	    daysPassed++;
	    dayIndex++;
	    if(dayIndex > 7)
		dayIndex = 1;
	}
	
	// How would I go about updating the minutes variable?
    }
    
    public static String getNameOfDay(int dayIndex){
	if(dayIndex == 2)
	    return "Tuesday";
	if(dayIndex == 3)
	    return "Wednesday";
	if(dayIndex == 4)
	    return "Thursday";
	if(dayIndex == 5)
	    return "Friday";
	if(dayIndex == 6)
	    return "Saturday";
	if(dayIndex == 7)
	    return "Sunday";
	
	return "Monday";
    }
    
    public float getSpeed(){
	return speed;
    }
    
    public void setSpeed(float speed){
	this.speed = speed;
    }
    
    public int getHours(){
	return hours;
    }
    
    public int getMinutes(){
	return hours;
    }
}

This is up to you to decide…

I would make minutes variable a float instead of int and do this in the update method.


public void update(float delta){

   float deltaMinutes = delta / 60; // assuming delta is in seconds

   minutes += deltaMinutes * speed;

   while(minutes >= 60) {
       hours++;
       minutes -= 60;
   }
   
   if(hours > 24){
       daysPassed++;
       dayIndex++;
       if(dayIndex > 7)
      dayIndex = 1;
   }
   
   // How would I go about updating the minutes variable?
    }

Thank you! That’s exactly what I needed.

You only need to have time stored in 1 variable, which has millisecond precision.


sec = millis / 1000 % 60;
min = millis / 1000 / 60 % 60;
hrs = millis / 1000 / 60 / 60 % 24;
day = millis / 1000 / 60 / 60 / 24;
dow = day % 7 + 1;

You can now perform arbitrary operations on ‘millis’ without having to keep track of overflows and underflows of all your variables.