Dan Dan - 3 months ago 25
Java Question

Java - Producing a timestamp for every minute of every hour for 24 hours

I am writing a program to produce a timestamp for every minute of every hour for a whole day.
I am using the Calendar class to get the timestamp, I have to use it so no point in suggesting other methods.

My idea to produce the file was to have a for loop for 24 hours and a nested for loop of 60 minutes in which the timestamp would be printed to the .dat file. I thought this would work and would print the data for the whole day and then stop.

However I was wrong, totally wrong!

The result is data being printed for every minute upto a date 2 years from now.

Here is my code so far;

public static void main (String [] args) throws FileNotFoundException
{
try
{
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
File fileName = new File(df.format(date) + ".dat");
RandomAccessFile raf = new RandomAccessFile(fileName, "rw");

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.add(Calendar.MILLISECOND, -cal.get(Calendar.MILLISECOND));
cal.add(Calendar.SECOND, -cal.get(Calendar.SECOND));
cal.add(Calendar.MINUTE, -cal.get(Calendar.MINUTE));
cal.add(Calendar.HOUR_OF_DAY, -cal.get(Calendar.HOUR_OF_DAY));

for(int hourInMinutes = 0; hourInMinutes < 1440; hourInMinutes++) //1440 is the total minutes in a day
{
for(int minute = 0; minute <= hourInMinutes; minute++)
{
raf.writeLong(cal.getTimeInMillis()); //Timestamp
cal.add(Calendar.MINUTE, 1);
}
}
raf.close();
}
catch(IOException iOE)
{
System.err.println(iOE);
}
}


The data starts at midnight (last night) and I want it to stop producing data at 11.59pm on the same day.

Anyone have any knowledge on how this is done?

aga aga
Answer

Your for loop looks wrong, here is the updated version:

 for(int hourInDay = 0; hourInDay < 24; hourInDay++) 
    {   
        for(int minute = 0; minute <= 59; minute++)
        {   
            raf.writeLong(cal.getTimeInMillis());
            cal.add(Calendar.MINUTE, 1);                    
        }
    }

Or you can get rid of an inner for loop (which has totally wrong second condition) and use the following version:

    for(int minutesInDay = 0; minutesInDay < 1440; minutesInDay++) //1440 is the total minutes in a day
    {   
        raf.writeLong(cal.getTimeInMillis());     
        cal.add(Calendar.MINUTE, 1);
    }

And try to give distinct names to your variables. hourInMinutes sounds for me like "the number of hours in one minute". Obviously, it's not what this variable stands for.

Comments