Search code examples
javacalendartimestampepoch

How to print data every minute using the Unix epoch in Java


I am writing code that will produce a .dat file in Java using RandomAccessFile.

Each file is created an hour long, so after every minute, new data is added, after the hour a new file is created.

For example - each file name is of the date/time format DD-MM-YY-HH. So now it would be 05-11-13-14 and the next one would be 05-11-13-15 and so on.

In the file I am collecting 5 pieces of data and the first piece is of a long value, which is the current timestamp of that time.

What I need is to get the timestamp to print results every minute.

Here is what I have done so far;

public static void main (String [] args) throws FileNotFoundException
{ 
    try
    {
        DateFormat df = new SimpleDateFormat("dd-MM-yy-HH");
        Date date = new Date();
        System.out.println(df.format(date));

        File fileName = new File(df.format(date) + ".dat");
        RandomAccessFile raf = new RandomAccessFile(fileName, "rw");

        for(int i = 0; i < 5; i++)
        {   
            //1383580800000 4/11/2013 4pm
            raf.writeLong(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis());
            raf.writeInt(10);
            raf.writeInt(2);
            raf.write((byte)1);
            raf.writeInt(3);        
        }
        raf.close();
    }
    catch(IOException iOE)
    {
        System.err.println(iOE);
    }
}

Solution

  • For simply printing the time stamp, all you have to do is date.getTime();. If you just want the epoch value there's absolutely no reason to touch any of the calendar or timezone classes.

    If you want to schedule something to run every minute, I would have a look at the ScheduledThreadPoolExecutor class, or simply a Timer.