java day of week_java – 设置DAY_OF_WEEK返回意外结果

我想将给定的日历实例的时间戳设置为一周的开头(星期一),而是返回一个看似完全不相关的时间戳 – 除非我在这之前访问任何日历的字段.我在下面提供了一个示例,请在Ideone中看到这个可运行的示例.

这是预期的行为吗?这背后的逻辑是什么?是的,我听说过Joda Time.

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Locale;

import java.util.TimeZone;

class MyTest {

private static Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"), Locale.FRANCE);

private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

public static void main(String[] args) {

// Set to any date.

calendar.set(2013, 10, 3);

System.out.println(dateFormat.format(calendar.getTime()));

// Set to another day.

calendar.set(2014, 0, 15);

// --- THE WTF STARTS HERE ---

// Uncommenting the line below returns the correct date in the end.

// calendar.getTime();

// Set to monday of current week.

calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());

// Expected outdate is 20140113

System.out.println(dateFormat.format(calendar.getTime()));

}

}

解决方法:

文档中的Field Manipulation章节清楚地解释了它.它虽然有点怪异.

Example: Consider a GregorianCalendar originally set to August 31, 1999. Calling

set(Calendar.MONTH, Calendar.SEPTEMBER) sets the date to September 31, 1999.

This is a temporary internal representation that resolves to October 1, 1999 if

getTime()is then called. However, a call to set(Calendar.DAY_OF_MONTH, 30) before the

call to getTime() sets the date to September 30, 1999, since no recomputation occurs

after set() itself.

编辑

从日历字段解决方案部分相同的文档

If there is any conflict in calendar field values, Calendar gives priorities to

calendar fields that have been set more recently. The following are the default

combinations of the calendar fields. The most recent combination, as determined

by the most recently set single field, will be used.

For the date fields:

YEAR + MONTH + DAY_OF_MONTH

YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK

YEAR + MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK

YEAR + DAY_OF_YEAR

YEAR + DAY_OF_WEEK + WEEK_OF_YEAR

我认为MONTH和DAY_OF_WEEK之间的差异就是这个.如果在最后一个语句中设置MONTH,它与YEAR MONTH DAY_OF_MONTH匹配并覆盖所有这些.如果设置DAY_OF_WEEK,则它与YEAR DAY_OF_WEEK WEEK_OF_YEAR匹配,因此不会覆盖月份值.或类似的东西.说实话,我看起来越多,看起来就越破碎.它完全没有意义.最好继续使用JodaTime

标签:java,calendar

来源: https://codeday.me/bug/20190529/1175671.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值