简体   繁体   English

将 DAY_OF_MONTH 或 DAY_OF_YEAR 添加到 Calendar 对象有什么区别?

[英]What's the difference between adding DAY_OF_MONTH or DAY_OF_YEAR to a Calendar object?

I want to increase a certain date by 1 day.我想将某个日期增加 1 天。 I create a Calendar object like:我创建了一个日历对象,如:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2012);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 31);

Then, for increasing it by 1 day, I can do 2 things :然后,为了增加 1 天,我可以做两件事:

cal.add(Calendar.DAY_OF_MONTH, 1);

OR要么

cal.add(Calendar.DAY_OF_YEAR, 1);

There are also other "DAY" constants, but I get the same result using the above 2 methods of increasing the day by 1. In which case will I get different results for the two?还有其他“DAY”常量,但使用上述 2 种将天数增加 1 的方法,我得到了相同的结果。在这种情况下,这两者会得到不同的结果吗?

For adding it really makes no difference, but this添加它确实没有区别,但这

Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.DAY_OF_MONTH));
System.out.println(c.get(Calendar.DAY_OF_YEAR));

prints印刷

28
363

Calendar.add Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. Calendar.add根据日历的规则在给定的日历字段中添加或减去指定的时间量。

Here you have a list of the fields of Calendar that you can add or subtract:在这里,您可以添加或减去日历字段列表:

  • MILLISECOND is the number of milliseconds between 0 and 999 MILLISECOND是 0 到 999 之间的毫秒数

  • SECOND is the number of seconds between 0 and 59 SECOND是 0 到 59 之间的秒数

  • MINUTE is the number of minutes between 0 and 59 MINUTE是 0 到 59 之间的分钟数

  • HOUR is the number of hours between 0 and 11 HOUR是 0 到 11 之间的小时数

  • HOUR_OF_DAY is the number of hours between 0 and 23 HOUR_OF_DAY是 0 到 23 之间的小时数

  • DAY_OF_WEEK is the day in relation of the week between 1 and 7 DAY_OF_WEEK是与 1 和 7 之间的周相关的天

  • DAY_OF_MONTH is the day in relation of the month between 1 and 31 DAY_OF_MONTH是与 1 到 31 之间的月份相关的日期

  • DAY_OF_YEAR is the day in relation of the year between 1 and 365 DAY_OF_YEAR是与 1 到 365 之间的年份相关的日期

  • WEEK_OF_MONTH is the week in relation of the month starting from 1 WEEK_OF_MONTH是从 1 开始的与月份相关的周

  • WEEK_OF_YEAR is the week in relation of the year starting from 1 WEEK_OF_YEAR是从 1 开始的与年份相关的周

  • MONTH is the month in relation of the year between 0 and 11 MONTH是与 0 到 11 之间的年份相关的月份

  • YEAR is the number of years starting from 1 YEAR是从 1 开始的年数

Hours, days and weeks have multiple fields but it doesn't matter which one you choose 1 .小时、天和周有多个字段,但您选择哪一个并不重要1 For example using -8 for DAY_OF_WEEK will work.例如,对DAY_OF_WEEK使用 -8 将起作用。

calendar.add(Calendar.DAY_OF_MONTH, -2); // subtract 2 days
calendar.add(Calendar.DAY_OF_WEEK, -2);  // subtract 2 days
calendar.add(Calendar.DAY_OF_YEAR, -2);  // subtract 2 days

calendar.add(Calendar.YEAR, -2);         // subtract 2 years

1 It doesn't matter only using Calendar.add , with other operations the results might be different. 1使用Calendar.add没有关系,其他操作结果可能不同。

Use Calendar.DATE for your purposes.Calendar.DATE用于您的目的。 In your case these three constants are synonyms.在您的情况下,这三个常量是同义词。

It doesn't make any difference when you call add.调用 add 时没有任何区别。 However the getters return different results :D然而,吸气剂返回不同的结果:D

code snippet from GregorianCalendar#add来自GregorianCalendar#add代码片段

case DAY_OF_MONTH: // synonym of DATE
 case DAY_OF_YEAR:
 case DAY_OF_WEEK:
    break;
DAY_OF_YEAR

Field number for get and set indicating the day number within the current year get 和 set 的字段编号表示当前年份中的天数

DAY_OF_MONTH

Field number for get and set indicating the day of the month . get 和 set 的字段编号,指示月份中的某一天 This is a synonym for DATE这是 DATE 的同义词

You will see difference if the day is greater than 31.如果一天大于 31,您将看到差异。

You essentially advance the date by one, in both the cases.在这两种情况下,您基本上都将日期提前了一个。 So there is no difference in both the approaches.所以这两种方法没有区别。

But sticking to a single method will render consistency across your codebase, maintainers will feel at home and probably the runtime optimizes the method call by compiling it as well.但是坚持使用单一方法将使您的代码库保持一致,维护人员会感到宾至如归,并且运行时可能也会通过编译来优化方法调用。

Actually, there can and will be a difference depending on what field type you choose:实际上,根据您选择的字段类型,可能会有差异:

* http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html * http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html

Usage model.使用模型。

To motivate the behavior of add() and roll(), consider a user interface component with increment and decrement buttons for the month, day, and year, and an underlying GregorianCalendar.为了激发 add() 和 roll() 的行为,考虑一个带有月、日和年递增和递减按钮的用户界面组件,以及一个底层的 GregorianCalendar。 If the interface reads January 31, 1999 and the user presses the month increment button, what should it read?如果界面显示 1999 年 1 月 31 日,用户按下月份递增按钮,它应该显示什么? If the underlying implementation uses set(), it might read March 3, 1999. A better result would be February 28, 1999. Furthermore, if the user presses the month increment button again, it should read March 31, 1999, not March 28, 1999. By saving the original date and using either add() or roll(), depending on whether larger fields should be affected, the user interface can behave as most users will intuitively expect.如果底层实现使用 set(),它可能会显示 1999 年 3 月 3 日。更好的结果是 1999 年 2 月 28 日。此外,如果用户再次按下月份增量按钮,它应该显示 1999 年 3 月 31 日,而不是 3 月 28 日, 1999。通过保存原始日期并使用 add() 或 roll(),根据是否应该影响较大的字段,用户界面可以像大多数用户直观地期望的那样运行。

tl;dr tl;博士

LocalDate.of( 2012 , Month.JANUARY , 31 )
    .plusDays( 1 )

2012-02-01 2012-02-01

…or… …要么…

LocalDate.of( 2012 , 1 , 31 )  // Sane numbering: 1-12 for January-December, and `2012` means year 2012.
    .plusDays( 1 )

2012-02-01 2012-02-01

java.time时间

The Calendar class is confusing, awkward, and poorly designed. Calendar类令人困惑、笨拙且设计不佳。 Among its many problems are these pass-the-units-flag methods.其众多问题之一是这些传递单位标志方法。 Fortunately, you can now forget all about this class.幸运的是,您现在可以忘记这个类的所有内容。

The java.time classes built into Java 8 and later now supplant the legacy date-time classes. Java 8 及更高版本中内置的java.time类现在取代了遗留的日期时间类。

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone. LocalDate类表示没有时间和时区的仅日期值。

A time zone is crucial in determining a date.时区对于确定日期至关重要。 For any given moment, the date varies around the globe by zone.对于任何给定时刻,日期因地区而异。 For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec .例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天”。

If no time zone is specified, the JVM implicitly applies its current default time zone.如果未指定时区,JVM 会隐式应用其当前默认时区。 That default may change at any moment, so your results may vary.该默认值可能随时更改,因此您的结果可能会有所不同。 Better to specify your desired/expected time zone explicitly as an argument.最好将您想要/预期的时区明确指定为参数。

Specify a proper time zone name in the format of continent/region , such as America/Montreal , Africa/Casablanca , or Pacific/Auckland .continent/region的格式指定正确的时区名称,例如America/MontrealAfrica/CasablancaPacific/Auckland Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).永远不要使用ESTIST等 3-4 个字母的缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM's current default time zone, ask for it and pass as an argument.如果您想使用 JVM 的当前默认时区,请询问它并作为参数传递。 If omitted, the JVM's current default is applied implicitly.如果省略,则隐式应用 JVM 的当前默认值。 Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.最好是明确的,因为 JVM 中任何应用程序的任何线程中的任何代码都可能在运行时随时更改默认值。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date.或指定日期。 You may set the month by a number, with sane numbering 1-12 for January-December.您可以通过数字设置月份,1-12 月的数字为 1-12。

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year.或者,更好的是使用预定义的Month枚举对象,一个用于一年中的每个月。 Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety .提示:在整个代码库中使用这些Month对象而不仅仅是整数,以使您的代码更具自文档性、确保有效值并提供类型安全

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Parts部分

With a LocalDate in hand, you may interrogate for its parts.有了LocalDate ,您就可以查询其部分。

To get the day-of-month, that is, the "date" such as 23 from January 23, 2018:要获取月份中的日期,即从 2018 年 1 月 23 23开始的“日期”,例如23

int dayOfMonth = ld.getDayOfMonth() ; // 1-31, depending on length of month.

To get the nth day of the year, from 1-365, or in a leap year, 1-366:要从 1-365 或闰年 1-366 获取一年中的第 n 天:

int dayOfYear = ld.getDayOfYear() ;

Math数学

Adding or subtracting days is quite simple and intuitive in java.time.在 java.time 中添加或减去天数非常简单和直观。 Convenience methods and span-of-time objects make the code much more clear.便捷方法和时间跨度对象使代码更加清晰。

LocalDate dayLater = ld.plusDays( 1 ) ;

So getting tomorrow would be:所以明天将是:

LocalDate tomorrow = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ).plusDays( 1 ) ;

Alternatively, you can represent a span-of-time unattached to the timeline.或者,您可以表示不附加到时间线的时间跨度。 For years-months-days, use Period .对于年-月-日,请使用Period For hours-minutes-seconds, use Duration .对于小时-分钟-秒,请使用Duration

Period p = Period.ofDays( 1 ) ;
LocalDate dayLater = ld.plus( p ) ;

Note that java.time uses sane numbering , unlike the legacy classes.请注意,与遗留类不同, java.time 使用合理的编号 The number 2018 is the year 2018. Months are numbered 1-12 for January-December.数字20182018年。 1-12 月的月份编号为 1-12。 Days of the week are numbered 1-7 for Monday-Sunday, per the ISO 8601 standard.根据ISO 8601标准,星期一至星期日的星期几编号为 1-7。


About java.time关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于 Java 8 及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .这些类取代麻烦的老传统日期时间类,如java.util.DateCalendar ,和SimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程 And search Stack Overflow for many examples and explanations.并在 Stack Overflow 上搜索许多示例和解释。 Specification is JSR 310 .规范是JSR 310

Where to obtain the java.time classes?从哪里获得 java.time 类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目用额外的类扩展了 java.time。 This project is a proving ground for possible future additions to java.time.该项目是未来可能添加到 java.time 的试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

In addition of date it does not make any difference whether you use DAY_OF_MONTH or DAY_OF_YEAR.除了日期之外,无论您使用 DAY_OF_MONTH 还是 DAY_OF_YEAR 都没有任何区别。 However, it makes sense when you get call getter and pass one of those.但是,当您获得 call getter 并传递其中一个时,这是有道理的。

Use DATE or DAY_OF_MONTH both are same使用 DATE 或 DAY_OF_MONTH 两者都相同

Here is the difference :这是区别:

DATE or DAY_OF_MONTH : Get and Set indicating the day of the month
DAY_OF_WEEK          : get and set indicating the week number within the current month
DAY_OF_YEAR          : get and set indicating the day number within the current ye

Source : https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html来源: https : //docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

   public static String findDay(int month, int day, int year) {
// Creating a calendar
  Calendar calndr = Calendar.getInstance();
     calndr.set(Calendar.MONTH, month-1);
     calndr.set(Calendar.YEAR, year);        
     calndr.set(Calendar.DAY_OF_MONTH, day);
     String[] strDays = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
                "Friday", "Saturday" };
      return strDays[calndr.get(Calendar.DAY_OF_WEEK)-1].toUpperCase();
    }

} }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java的Calendar类中Calendar.WEEK_OF_MONTH和Calendar.DAY_OF_WEEK_IN_MONTH有什么区别? - What is the difference between Calendar.WEEK_OF_MONTH and Calendar.DAY_OF_WEEK_IN_MONTH in Java's Calendar class? 日历.YEAR,.MONTH,DAY_OF_MONTH与date.getDay()等不同? - Calendar .YEAR, .MONTH, DAY_OF_MONTH different than date.getDay() etc? 无法使用Java更改日历DAY_OF_MONTH - Can't change Calendar DAY_OF_MONTH in Java 与 Calendar.DATE 和 Calendar.DAY_OF_MONTH 有什么区别? - What's the difference from Calendar.DATE and Calendar.DAY_OF_MONTH? Java Calendar实例增加DAY_OF_MONTH作为递减(仅)HOUR或MINUTE的副作用 - Java Calendar instance increments DAY_OF_MONTH as a side effect of decrementing (only) HOUR or MINUTE java 中的 Calendar.getInstance().get(Calendar.DAY_OF_WEEK) 和 Calander.DAY_OF_WEEK 有什么区别 - What's the difference between Calendar.getInstance().get(Calendar.DAY_OF_WEEK) and Calander.DAY_OF_WEEK in java 使用CALENDAR将月份和日期数字转换为一年中的日期 - Convert month and day number to day of year using CALENDAR 如何格式化从用户获得的日期作为输入,然后在日历中找到该日期以找出该日历中的day_of_month? - how do i format date that i get from user as input and then find that date in a calendar to find out which day_of_month is it in that calendar? 根据年份和年份开始日期显示日历月(Java) - Display calendar month based off of the year and day the year starts (Java) 设置 calendar.day_of_month 就是设置 calendar.year - Seting calendar.day_of_month is setting calendar.year
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM