如何使Java日历月返回周日的月份?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (53)

现有一个SQL数据库,有一个年和周字段,我需要获得月份数据。例如,从2019.01.28到2019.02.01周,我得到了第二个月。

代码如下所示:

rs = stmt.executeQuery("SELECT * FROM " + sqlDatabase.beosztas() + " WHERE id = \'" + id + "\'");`
        ResultSetMetaData md = rs.getMetaData();
        while (rs.next()) {
            year = rs.getInt(2);
            week = rs.getInt(3);
            cal.set(Calendar.YEAR, year);
            cal.set(Calendar.WEEK_OF_YEAR, week);
            cal.set(Calendar.DAY_OF_WEEK, 1);
            if (count == 0) {
                month = cal.get(Calendar.MONTH) + 1;
            }
            count++;
        }
提问于
用户回答回答于

这样试试:

cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

Calendar cal = Calendar.getInstance();
cal.set(2018, 2, 18); // wrong. here the date will be 2018-01-18
cal.set(2018, Calendar.FEBRUARY, 18); // correct
用户回答回答于

试试以下方法:

int year = 2019;
int week = 5;

Calendar cal = Calendar.getInstance(Locale.US);
cal.clear();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
System.out.println(cal.getTime());

cal = Calendar.getInstance(Locale.FRANCE);
cal.clear();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
System.out.println(cal.getTime());

输出:

Sun Jan 27 00:00:00 EST 2019
Mon Jan 28 00:00:00 EST 2019

在这两种情况下,将得到一月。

输出:

Sun Mar 31 00:00:00 EDT 2019
Mon Apr 01 00:00:00 EDT 2019

扫码关注云+社区

领取腾讯云代金券