Total Pageviews

2018/08/06

[Java] How to compare two string dates in Java?

Scenario

The format of string date is yyyyMMdd, ex. 20180806

How-To
Here has sample code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
    @PostMapping(value = "/{utterTemplateId}/utterances/save")
    public @ResponseBody List<Utterance> saveUtterance(@PathVariable Integer utterTemplateId,
            @RequestBody Utterance utterance, Alerter alerter) {
        
        Boolean hasStartDate = !Strings.isNullOrEmpty(utterance.getStartDate());
        Boolean hasEndDate = !Strings.isNullOrEmpty(utterance.getEndDate());
        if ((hasStartDate && !hasEndDate) || (!hasStartDate && hasEndDate)) {
            throw new RuntimeException("請輸入完整上下架日期");
        }
        
        if (hasStartDate && hasEndDate) {
            String startDate = utterance.getStartDate();
            String endDate = utterance.getEndDate();
            DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            try {
                if (dateFormat.parse(startDate).after(dateFormat.parse(endDate))) {
                    throw new RuntimeException("下架日期不可早於上架日期");
                }
            } catch (ParseException e) {
                throw new RuntimeException("上下架日期解析發生錯誤, 錯誤原因: " + e.getMessage(), e);
            }
        }
        
        // ignore some code
    }

No comments: