【问题标题】:SimpleDateFormat.format(currentDate) does not change currentDate variable [duplicate]SimpleDateFormat.format(当前日期)不会更改当前日期变量[重复]
【发布时间】:2020-06-06 23:07:10
【问题描述】:

当我在我的 servlet 中做这样的事情时,我仍然得到像 Sun Jun 07 00:59:46 CEST 2020 这样的日期格式,但我想让它像 2020.06.07 一样

我的 servlet 中的代码:

SimpleDateFormat sdfo = new SimpleDateFormat("yyyy-MM-dd");
Date currentDate = new Date();
sdfo.format(currentDate);
request.setAttribute("currentDate", currentDate);

还有我的jsp文件:

Current date: <c:out value="${currentDate}"/>

我应该在这里改变什么?

【问题讨论】:

    标签: java date simpledateformat


    【解决方案1】:

    您已将currentDate 而不是格式化的日期字符串设置为request

    替换

    sdfo.format(currentDate);
    request.setAttribute("currentDate", currentDate);
    

    String today = sdfo.format(currentDate);
    request.setAttribute("currentDate", today);
    

    我还建议你使用java.time.LocalDateDateTimeFormatter.ofPattern,而不是使用过时的java.util.DateSimpleDateFormat,如下所示:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDate currentDate = LocalDate.now();
    String today = currentDate.format(formatter);
    request.setAttribute("currentDate", today);
    

    查看this 了解有关现代日期/时间 API 的更多信息。

    【讨论】:

    • 好吧,它工作得很好,但现在日期是String,我想保持它像Date一样,因为我想比较日期。有可能吗?
    • 如果你想设置为Date,你必须把它格式化成JSP。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    相关资源
    最近更新 更多