Marjer
Marjer

Reputation: 1403

How to generate a file with current Day's hour with minute upto current time using Calendar

How to generate a file with current Day's hour with minute upto current time.Using calendar in java

For example if the time is 02:28, i want the hour and minute as below.

Output:
00:00
00:01
00:02
00:03
.
.
.
.
02:28

Upvotes: 0

Views: 103

Answers (2)

Bohemian
Bohemian

Reputation: 425083

Using an arithmetic approach, ie without using Calendar, it's only a few of lines:

long now = System.currentTimeMillis();
int offset = TimeZone.getDefault().getOffset(now);
int minutes = (int)((now + offset) % (24 * 3600000)) / 60000;
for (int i = 0; i <= minutes; i++)
    System.out.format("%02d:%02d\n", i / 60, i % 60);

Output is as per your post.

Upvotes: 1

Jens
Jens

Reputation: 69460

Try this code:

    FileWriter fileWriter = new FileWriter("myFile");
    Calendar now = new GregorianCalendar();

    Calendar c = new GregorianCalendar();
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);

    DateFormat df = new SimpleDateFormat("HH:mm");
    while (c.before(now)) {
        c.add(Calendar.MINUTE, 1);
        fileWriter.write(df.format(c.getTime())+System.lineSeparator());
    }

    fileWriter.close();

Upvotes: 1

Related Questions