I need to generate Unix timestamp in milliseconds for every next day at a definite time.
For example: today is 4/11/2021 at 09:00:00 then timestamp is: 1636002000000
for tomorrow I need 5/11/2021 at 09:00:00
day after tomorrow 6/11/2021 at 09:00:00
and so on...
so how can I get auto generated timestamp for same in Java?
Like Samuel Marchant I recommend that you use java.time, the modern Java date and time API, for your date and time work.
If you want every day at 9, define that as a constant first:
private static final LocalTime TIME = LocalTime.of(9, 0);
Now your milliseconds values can be obtained in this way:
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.systemDefault()).with(TIME);
for (int i = 0; i < 10; i++) {
long timestampMillis = zdt.toInstant().toEpochMilli();
System.out.format("%-30s %13d%n", zdt, timestampMillis);
zdt = zdt.plusDays(1);
}
Output when I ran the code just now:
2021-11-11T09:00+01:00[Europe/Paris] 1636617600000 2021-11-12T09:00+01:00[Europe/Paris] 1636704000000 2021-11-13T09:00+01:00[Europe/Paris] 1636790400000 2021-11-14T09:00+01:00[Europe/Paris] 1636876800000 2021-11-15T09:00+01:00[Europe/Paris] 1636963200000 2021-11-16T09:00+01:00[Europe/Paris] 1637049600000 2021-11-17T09:00+01:00[Europe/Paris] 1637136000000 2021-11-18T09:00+01:00[Europe/Paris] 1637222400000 2021-11-19T09:00+01:00[Europe/Paris] 1637308800000 2021-11-20T09:00+01:00[Europe/Paris] 1637395200000
Please enjoy not only how much simpler but first and foremost how much more natural to read the code is compared to the code in your own answer. This is typical for java.time compared to the old and poorly designed classes from Java 1.0 and 1.1.
Oracle Tutorial: Date Time explaining how to use java.time.