У меня есть Angular Frontend с Java Backend, и я хотел бы использовать DateNput PrimeNG для получения и сохранения даты.Для этого я получил следующий код:
<p-calendar [(ngModel)]="enddate" dateFormat="dd.mm.yy" class="medium-field"></p-calendar>
и в моем компоненте:
enddate: Date;
При отправке этого значения через REST у меня есть следующий код (включая проверку):
createPSP(project_num: string, financialItem: FinancialItem) {
this.logger.info("Startdate is " + financialItem.startDate);
this.logger.info("Enddate is " + financialItem.endDate);
let order_num = financialItem.orderNumber;
let psp_num = financialItem.pspNumber;
return this.http.post(`${httpBaseUrl}/project/${project_num}/order/${order_num}/addFinancialItem/${psp_num}`, financialItem).pipe();
}
Вывод (который является правильным):
Затем я сохраняю его в своем бэкэнде в LocalDate
-вариате (который преобразуется в date
-типа в MySQL).Теперь, что происходит, я вставляю 31.12.2018
и получаю (в моем конвертере в бэкэнде) 30.12.2018
и в MySQL 29.12.2018
.Почему это так?
Редактировать: Когда я изменяю LocalDate
на LocalDateTime
, я просто получаю 30.12.2018
в MySQL вместо 29.12.2018
, что, очевидно, все еще неправильно.
Еще немного кода:
Я определил свой MySQL-столбец следующим образом (в моей сущности):
@Entity
class FinancialItemDto {
//...
@Column(name = "ENDDATE", nullable = false)
private LocalDate endDate;
}
В контроллере:
public ResponseEntity addFinancialItem(@PathVariable String project_num, @PathVariable String order_num,
@PathVariable String psp_num, @RequestBody FinancialItemDto financialItemDto) {
try {
this.financialItemService.saveItemGivenProjectAndOrderNumber(financialItemDto, order_num);
} catch (NoSuchEntityException e) {
this.logger.error(e.getMessage());
return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getUserMessage());
}
return ResponseEntity.ok(HttpStatus.OK);
}
В службе:
@Transactional
@Override
public void saveItemGivenProjectAndOrderNumber(FinancialItemDto financialItemDto, String orderNumber)
throws NoSuchEntityException {
OrderEntity order = this.orderRepository.findByOrderNumber(orderNumber).orElseThrow(
() -> new NoSuchEntityException("Order with number " + orderNumber + " could not be found.",
"Der Abruf wurde nicht gefunden."));
OrdertypesEntity ordertype = this.ordertypesRepository.findByShorthand(financialItemDto.getOrderType())
.orElseThrow(() -> new NoSuchEntityException("Ordertype " + financialItemDto.getOrderType()
+ " for creating FI to order " + orderNumber + " could not be found.",
"Der Abruftyp wurde nicht gefunden."));
FinancialItemEntity financialItemEntity = FinancialItemConverter.dtoToEntity(financialItemDto, ordertype,
order);
this.entityManager.persist(financialItemEntity);
}
Dto на стороне TS определяет дату следующим образом:
export class FinancialItem {
endDate: Date;
//...
}
Мой конвертер просто передает:
public static FinancialItemEntity dtoToEntity(FinancialItemDto financialItemDto, OrdertypesEntity ordertype, OrderEntity order) {
FinancialItemEntity financialItemEntity = new FinancialItemEntity( (...), financialItemDto.getEndDate(), (...));
LoggerFactory.getLogger(FinancialItemConverter.class).info("Got Date Value: " + financialItemDto.getEndDate()); //gives: Got Date Value: 2018-12-30 instead of value 31.12.2018
return financialItemEntity;
}
Обновление:
Временное решение для "REST-Service", чтобы "потерять"один день сохранял дату в длинном формате, а затем передавал ее и преобразовывал обратно.К сожалению, при вызове функции repository.save()
регистратор вызывает, что когда я вставил 2018-12-01
, значение даты также равно 2018-12-01
, но MySQL говорит, что в моей базе данных оно 2018-11-30
.Я не могу разобрать, что там происходит:
this.logger.info("Startdate is " + financialItemDto.getStartDate()); //2018-12-01
this.logger.info("Startdate is " + financialItemEntity.getStartDate()); //2018-12-01
this.financialItemRepository.save(financialItemEntity);
this.logger.info("Startdate (received) is " + this.financialItemRepository.getFinancialItemByPSPNumber(financialItemDto.getPspNumber()).get().getStartDate()); //2018-12-01