diff --git a/src/main/java/core/basesyntax/SalaryInfo.java b/src/main/java/core/basesyntax/SalaryInfo.java index 2754b0c17..fcc575fb8 100644 --- a/src/main/java/core/basesyntax/SalaryInfo.java +++ b/src/main/java/core/basesyntax/SalaryInfo.java @@ -1,25 +1,30 @@ package core.basesyntax; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; import java.util.Objects; public class SalaryInfo { + private static final int DATE = 0; + private static final int NAME = 1; + private static final int HOURS = 2; + private static final int INCOME = 3; + private static final int DAY = 1; + private static final String DATE_FORMAT = "dd.MM.yyyy"; + public String getSalaryInfo(String[] names, String[] data, String dateFrom, String dateTo) { - Calendar dateFromDateFormat = changeDateFormat(dateFrom); - Calendar dateToDateFormat = changeDateFormat(dateTo); - dateFromDateFormat.add(Calendar.DAY_OF_MONTH, -1); - dateToDateFormat.add(Calendar.DAY_OF_MONTH, 1); + LocalDate dateFromDateFormat = changeDateFormat(dateFrom); + LocalDate dateToDateFormat = changeDateFormat(dateTo); int[] salary = new int[names.length]; for (String dataRow : data) { String[] dataInfo = dataRow.split(" "); - if (changeDateFormat(dataInfo[0]).after(dateFromDateFormat) - && changeDateFormat(dataInfo[0]).before(dateToDateFormat)) { + if (changeDateFormat(dataInfo[DATE]).isAfter(dateFromDateFormat.minusDays(DAY)) + && changeDateFormat(dataInfo[DATE]).isBefore(dateToDateFormat.plusDays(DAY))) { for (int i = 0; i < names.length; i++) { - if (Objects.equals(names[i], dataInfo[1])) { - salary[i] += Integer.parseInt(dataInfo[2]) * Integer.parseInt(dataInfo[3]); + if (Objects.equals(names[i], dataInfo[NAME])) { + salary[i] += Integer.parseInt(dataInfo[HOURS]) + * Integer.parseInt(dataInfo[INCOME]); } } } @@ -39,17 +44,8 @@ && changeDateFormat(dataInfo[0]).before(dateToDateFormat)) { return stringBuilder.toString(); } - public Calendar changeDateFormat(String stringDate) { - SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy"); - - Calendar calendar = Calendar.getInstance(); - - try { - calendar.setTime(sdf.parse(stringDate)); - } catch (ParseException e) { - e.printStackTrace(); - } - - return calendar; + public LocalDate changeDateFormat(String stringDate) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT); + return LocalDate.parse(stringDate, formatter); } }