【发布时间】:2018-10-23 11:41:17
【问题描述】:
根据https://en.wikipedia.org/wiki/ISO_8601#Week_dates,工作日从星期一开始。但是,从 Java 中,如果您尝试以两种不同的方式提取周数,如果日期是星期日,则会出现两个不同的输出。
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class TestDate {
public static void main(String[] args) throws ParseException {
final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
final SimpleDateFormat weekFormatter = new SimpleDateFormat("ww");
String date = "2018-10-21";
System.out.println(weekFormatter.format(formatter.parse(date)));
Calendar calendar = Calendar.getInstance();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setTime(formatter.parse(date));
System.out.println(calendar.get(Calendar.WEEK_OF_YEAR));
}
}
输出:
43
42
这是不一致吗?
这只是我为重现问题而编写的一个测试程序,我注意到 Hive 中的问题,如下所示:
0: jdbc:hive2://zk0-something> select from_unixtime(t, 'ww'), weekofyear(from_unixtime(t, 'yyyy-MM-dd')) from (select 1540122033 as t) a;
+------+------+--+
| _c0 | _c1 |
+------+------+--+
| 43 | 42 |
+------+------+--+
1 row selected (0.388 seconds)
0: jdbc:hive2://zk0-something>
【问题讨论】:
-
不要怪
SimpleDateFormat,要怪你的默认语言环境将星期日定义为一周的第一天。如果您想要“正确”的值(嗯,取决于观点),然后使用将星期一定义为一周第一天的国家/地区的语言环境,例如法国 (new SimpleDateFormat("ww", Locale.FRANCE)) -
我建议你避免使用
SimpleDateFormat类。它不仅过时了,而且出了名的麻烦。今天我们在java.time, the modern Java date and time API 的表现要好得多。
标签: java hive simpledateformat datetime-format week-number