I want to rename my file name according to yyyy_[DayOfTheYear]. The day of the year should be in 3 digits always. For example, 01-01-2021 -> 2021_001 ; 31-01-2021 -> 2021_031 ; 31-12-2021 -> 2021_365 Is there any predefined method to get the 3 digits in Java?
Asked
Active
Viewed 201 times
0
-
There are two separate problems here - retrieving the day of year, and padding 0s to the left. Which one are you asking about? – Sweeper Feb 03 '21 at 12:20
-
@Sweeper padding 0s to the left is obviously like the last option. Getting the day is not difficult but my question was for getting the day in 3 digits by default without any padding. – Shivam Thakur Feb 03 '21 at 12:28
1 Answers
2
Check LocalDate::getDayOfYear()
.
The instance of LocalDate
may be formatted using String.format
or using DateTimeFormatter::ISO_ORDINAL_DATE
. The latter allows to get year and day of year, however, these values are delimited with '-'
, which can be replaced if necessary.
Example:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class MyClass {
public static void main(String args[]) {
LocalDate today = LocalDate.now();
DateTimeFormatter yearDayOfYear = DateTimeFormatter.ISO_ORDINAL_DATE;
System.out.printf("%s -> %4d_%03d%n", today, today.getYear(), today.getDayOfYear());
System.out.printf("%s -> %s%n", today, today.format(yearDayOfYear).replace('-', '_'));
}
}
Output:
2021-02-03 -> 2021_034
2021-02-03 -> 2021_034

Nowhere Man
- 19,170
- 9
- 17
- 42
-
It doesn't return 3 digits. For 01-01-2021 it returns 1, not 001. – Shivam Thakur Feb 03 '21 at 12:24
-
1DecimalFormat df = new DecimalFormat("000"); System.err.println(df.format(LocalDate.now().getDayOfYear())); – Saikat Feb 03 '21 at 12:25
-