首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我从JSP向servlet发送一个月类型字符串,然后从servlet向dao发送。如何从这个字符串中获取年份和月份?

我从JSP向servlet发送一个月类型字符串,然后从servlet向dao发送。如何从这个字符串中获取年份和月份?
EN

Stack Overflow用户
提问于 2019-02-10 14:42:16
回答 1查看 151关注 0票数 0

我应该如何在mysql中将字符串转换为Year-MMMM格式,还是必须在控制器部分转换它?假设: 2019-02保存为2019-02,但我想要另一列将2019-02转换为2019-2月。

JSP部分

代码语言:javascript
运行
复制
<form action="YearMonthController" method="post">

    <input type="hidden" name="command" value="CREATE_YearMonth" />

    Month with year: <input type="month" name="year_month">

    <input type="submit">

</form>

这是控制器部分

代码语言:javascript
运行
复制
private void create_a_yearMonth_controller(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String _yearMonth = request.getParameter("year_month");

    YM ym = new YM(_yearMonth);

    _ymDAO.create_a_yearMonth_dao(ym);

}

这是DAO部分

代码语言:javascript
运行
复制
public void create_a_yearMonth_dao(YM ym) throws Exception {

    Connection connection = null;
    PreparedStatement prepared_statement = null;

    try {
        connection = data_source.getConnection();

        String sql = "INSERT INTO `years_months`\r\n" + "(yearMonth) \r\n" + "VALUES \r\n" + "(?);";

        prepared_statement = connection.prepareStatement(sql);

        prepared_statement.setString(1, ym.get_yearMonth());

        prepared_statement.execute();
    } finally {
        close(connection, prepared_statement, null);
    }

}

这是一张桌子

代码语言:javascript
运行
复制
CREATE TABLE `years_months` (
yearMonth VARCHAR(50) NOT NULL,
PRIMARY KEY (yearMonth)
);
EN

回答 1

Stack Overflow用户

发布于 2019-02-10 16:37:23

因为MySQL没有year-month数据类型(至少我认为没有),所以我总是将year和month单独存储为2019-02 (因此varchar(50)列非常宽,char(7)也可以)。这是广泛认可的ISO 8601格式。

在Java语言中,我会使用YearMonth来表示年份和月份(不需要创建自己的类)。并根据演示需要对其进行格式化。YearMonth.toString生成上述ISO8601格式,然后YearMonth.parse将其解析回来,因此所有内容都能很好地结合在一起。

代码语言:javascript
运行
复制
public void createAYearMonthDao(YearMonth ym) throws SQLException {
    String sql = "INSERT INTO `years_months` (yearMonth) VALUES (?);";

    try (Connection connection = data_source.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
        preparedStatement.setString(1, ym.toString());
        preparedStatement.execute();
    }
}

要在需要时生成像2019-February这样的字符串:

代码语言:javascript
运行
复制
    DateTimeFormatter ymFormatter = DateTimeFormatter.ofPattern("uuuu-MMMM", Locale.ENGLISH);

    YearMonth ym = YearMonth.of(2019, Month.FEBRUARY);
    String formattedYm = ym.format(ymFormatter);
    System.out.println(formattedYm);

输出:

2019-2月

YearMonth有分别获取年和月的方法,例如:

代码语言:javascript
运行
复制
    System.out.println("Year " + ym.getYear() + " month " + ym.getMonth());

年2019月2月

注释中的另一个建议在MySQL中使用date,在Java中使用LocalDate也不错。优点:您可以在保存和检索时保存格式化和解析。缺点:您的数据库中有一个冗余的月日。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54614026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档