java.util.Calendar类的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(18.9k)|赞(0)|评价(0)|浏览(134)

本文整理了Java中java.util.Calendar类的一些代码示例,展示了Calendar类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Calendar类的具体详情如下:
包路径:java.util.Calendar
类名称:Calendar

Calendar介绍

[英]Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on. (A Date object represents a specific instant in time with millisecond precision. See Date for information about the Date class.)

Subclasses of Calendar interpret a Dateaccording to the rules of a specific calendar system.

Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a default instance of this class for general use. Calendar's getInstance method returns a calendar whose locale is based on system settings and whose time fields have been initialized with the current date and time:

Calendar rightNow = Calendar.getInstance()

A Calendar object can produce all the time field values needed to implement the date-time formatting for a particular language and calendar style (for example, Japanese-Gregorian, Japanese-Traditional). Calendar defines the range of values returned by certain fields, as well as their meaning. For example, the first month of the year has value MONTH == JANUARY for all calendars. Other values are defined by the concrete subclass, such as ERAand YEAR. See individual field documentation and subclass documentation for details.

When a Calendar is lenient, it accepts a wider range of field values than it produces. For example, a lenient GregorianCalendar interprets MONTH == JANUARY, DAY_OF_MONTH == 32 as February 1. A non-lenient GregorianCalendar throws an exception when given out-of-range field settings. When calendars recompute field values for return by get(), they normalize them. For example, a GregorianCalendar always produces DAY_OF_MONTHvalues between 1 and the length of the month.

Calendar defines a locale-specific seven day week using two parameters: the first day of the week and the minimal days in first week (from 1 to 7). These numbers are taken from the locale resource data when a Calendar is constructed. They may also be specified explicitly through the API.

When setting or getting the WEEK_OF_MONTH or WEEK_OF_YEAR fields, Calendar must determine the first week of the month or year as a reference point. The first week of a month or year is defined as the earliest seven day period beginning on getFirstDayOfWeek() and containing at least getMinimalDaysInFirstWeek() days of that month or year. Weeks numbered ..., -1, 0 precede the first week; weeks numbered 2, 3,... follow it. Note that the normalized numbering returned by get() may be different. For example, a specific Calendar subclass may designate the week before week 1 of a year as week n of the previous year.

When computing a Date from time fields, two special circumstances may arise: there may be insufficient information to compute the Date (such as only year and month but no day in the month), or there may be inconsistent information (such as "Tuesday, July 15, 1996" -- July 15, 1996 is actually a Monday).

Insufficient information. The calendar will use default information to specify the missing fields. This may vary by calendar; for the Gregorian calendar, the default for a field is the same as that of the start of the epoch: i.e., YEAR = 1970, MONTH = JANUARY, DATE = 1, etc.

Inconsistent information. If fields conflict, the calendar will give preference to fields set more recently. For example, when determining the day, the calendar will look for one of the following combinations of fields. The most recent combination, as determined by the most recently set single field, will be used.

MONTH + DAY_OF_MONTH 
MONTH + WEEK_OF_MONTH + DAY_OF_WEEK 
MONTH + DAY_OF_WEEK_IN_MONTH + DAY_OF_WEEK 
DAY_OF_YEAR 
DAY_OF_WEEK + WEEK_OF_YEAR

For the time of day:

HOUR_OF_DAY 
AM_PM + HOUR

Note: There are certain possible ambiguities in interpretation of certain singular times, which are resolved in the following ways:

  1. 24:00:00 "belongs" to the following day. That is, 23:59 on Dec 31, 1969 < 24:00 on Jan 1, 1970 < 24:01:00 on Jan 1, 1970 form a sequence of three consecutive minutes in time.
  2. Although historically not precise, midnight also belongs to "am", and noon belongs to "pm", so on the same day, we have 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm

The date or time format strings are not part of the definition of a calendar, as those must be modifiable or overridable by the user at runtime. Use java.text.DateFormat to format dates.

Field manipulation methods

Calendar fields can be changed using three methods: set(), add(), and roll().

set(f, value) changes field fto value. In addition, it sets an internal member variable to indicate that field f has been changed. Although field f is changed immediately, the calendar's milliseconds is not recomputed until the next call to get(), getTime(), or getTimeInMillis() is made. Thus, multiple calls to set() do not trigger multiple, unnecessary computations. As a result of changing a field using set(), other fields may also change, depending on the field, the field value, and the calendar system. In addition, get(f) will not necessarily return value after the fields have been recomputed. The specifics are determined by the concrete calendar class.

Example: Consider a GregorianCalendar originally set to August 31, 1999. Calling set(Calendar.MONTH, Calendar.SEPTEMBER) sets the calendar 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 calendar to September 30, 1999, since no recomputation occurs after set() itself.

add(f, delta) adds delta to field f. This is equivalent to calling set(f, get(f) + delta) with two adjustments:
Add rule 1. The value of field f after the call minus the value of field f before the call is delta, modulo any overflow that has occurred in field f. Overflow occurs when a field value exceeds its range and, as a result, the next larger field is incremented or decremented and the field value is adjusted back into its range.

Add rule 2. If a smaller field is expected to be invariant, but   it is impossible for it to be equal to its prior value because of changes in its minimum or maximum after field f is changed, then its value is adjusted to be as close as possible to its expected value. A smaller field represents a smaller unit of time. HOUR is a smaller field than DAY_OF_MONTH. No adjustment is made to smaller fields that are not expected to be invariant. The calendar system determines what fields are expected to be invariant.

In addition, unlike set(), add() forces an immediate recomputation of the calendar's milliseconds and all fields.

Example: Consider a GregorianCalendar originally set to August 31, 1999. Calling add(Calendar.MONTH, 13) sets the calendar to September 30, 2000. Add rule 1 sets the MONTH field to September, since adding 13 months to August gives September of the next year. Since DAY_OF_MONTH cannot be 31 in September in a GregorianCalendar, add rule 2 sets the DAY_OF_MONTH to 30, the closest possible value. Although it is a smaller field, DAY_OF_WEEK is not adjusted by rule 2, since it is expected to change when the month changes in a GregorianCalendar.

roll(f, delta) adds delta to field f without changing larger fields. This is equivalent to calling add(f, delta) with the following adjustment:
Roll rule. Larger fields are unchanged after the call. A larger field represents a larger unit of time. DAY_OF_MONTH is a larger field than HOUR.

Example: Consider a GregorianCalendar originally set to August 31, 1999. Calling roll(Calendar.MONTH, 8) sets the calendar to April 30, 1999. Add rule 1 sets the MONTH field to April. Using a GregorianCalendar, the DAY_OF_MONTH cannot be 31 in the month April. Add rule 2 sets it to the closest possible value, 30. Finally, the roll rule maintains the YEAR field value of 1999.

Example: Consider a GregorianCalendar originally set to Sunday June 6, 1999. Calling roll(Calendar.WEEK_OF_MONTH, -1) sets the calendar to Tuesday June 1, 1999, whereas calling add(Calendar.WEEK_OF_MONTH, -1)sets the calendar to Sunday May 30, 1999. This is because the roll rule imposes an additional constraint: The MONTH must not change when the WEEK_OF_MONTH is rolled. Taken together with add rule 1, the resultant date must be between Tuesday June 1 and Saturday June 5. According to add rule 2, the DAY_OF_WEEK, an invariant when changing the WEEK_OF_MONTH, is set to Tuesday, the closest possible value to Sunday (where Sunday is the first day of the week).

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. If the interface reads January 31, 1999 and the user presses the month increment button, what should it read? 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.

Note: You should always use roll and add rather than attempting to perform arithmetic operations directly on the fields of a Calendar. It is quite possible for Calendar subclasses to have fields with non-linear behavior, for example missing months or days during non-leap years. The subclasses' add and roll methods will take this into account, while simple arithmetic manipulations may give invalid results.
[中]Calendar是一个抽象基类,用于在日期对象和一组整数字段(如年、月、日、小时等)之间进行转换。(日期对象以毫秒精度表示特定的时间瞬间。有关日期类的信息,请参见日期。)
日历的子类根据特定日历系统的规则解释日期。
与其他对区域设置敏感的类一样,Calendar提供了一个类方法getInstance,用于获取此类的默认实例以供一般使用。Calendar的getInstance方法返回一个日历,其区域设置基于系统设置,其时间字段已使用当前日期和时间初始化:

Calendar rightNow = Calendar.getInstance()

日历对象可以生成实现特定语言和日历样式(例如,日文公历、日文繁体)的日期-时间格式所需的所有时间字段值。日历定义某些字段返回的值的范围及其含义。例如,对于所有日历,一年中的第一个月的值为month==一月。其他值由具体子类定义,例如era和YEAR。有关详细信息,请参阅单个字段文档和子类文档。
当日历为“宽松”时,它接受的字段值范围比它产生的范围更广。例如,宽大的GregorianCalendar将月份==1月,月中日==32解释为2月1日。当给出超出范围的字段设置时,不宽容的GregorianCalendar会引发异常。当日历重新计算get()返回的字段值时,它们会对其进行规范化。例如,GregorianCalendar始终生成介于1和月份长度之间的DAY_OF_monthv值。
日历使用两个参数定义特定于区域设置的七天工作周:一周的第一天和第一周的最短天数(从1到7)。这些数字是在构建日历时从区域设置资源数据中获取的。它们也可以通过API显式指定。
设置或获取月份的周或年份的周字段时,日历必须确定月份或年份的第一周作为参考点。一个月或一年的第一周定义为从getFirstDayOfWeek()开始并至少包含该月或一年的getMinimalDaysInFirstWeek()天的最早七天期间。周数-1,0先于第一周;第2周、第3周,。。。跟着它走。请注意,get()返回的规范化编号可能不同。例如,特定的日历子类可以将一年中第1周之前的一周指定为上一年的第n周。
从时间域计算日期时,可能会出现两种特殊情况:可能没有足够的信息来计算日期(例如,只有年和月,但在月中没有天),或者可能存在不一致的信息(例如“1996年7月15日,星期二”--1996年7月15日实际上是星期一)。
信息不足。日历将使用默认信息指定缺少的字段。这可能因日历而异;对于公历,字段的默认值与纪元开始时的默认值相同:即年=1970年,月=一月,日期=1,等等。
信息不一致。如果字段冲突,日历将优先选择最近设置的字段。例如,在确定日期时,日历将查找以下字段组合之一。将使用由最近设置的单个字段确定的最新组合。
每天的时间:

HOUR_OF_DAY 
AM_PM + HOUR

注:某些单数时间的解释可能存在某些歧义,可通过以下方式解决:
1.24:00:00“属于”第二天。也就是说,1969年12月31日23:59<1970年1月1日24:00<1970年1月1日24:01:00形成了连续三分钟的时间序列。
1.虽然历史上并不精确,但午夜也属于“上午”,中午属于“下午”,因此在同一天,我们有上午12:00(午夜)<12:01上午,下午12:00(中午)<12:01下午
日期或时间格式字符串不是日历定义的一部分,因为这些字符串必须在运行时可由用户修改或覆盖。使用java。文本DateFormat可设置日期格式。
现场操作方法
可以使用三种方法更改日历字段:set()、add()和roll()。
设置(f,值)更改字段fto值。此外,它还设置了一个内部成员变量,以指示字段f已更改。虽然字段f会立即更改,但在下一次调用get()、getTime()或getTimeInMillis()之前,不会重新计算日历的毫秒数。因此,多次调用set()不会触发多次不必要的计算。使用set()更改字段后,其他字段也可能会更改,具体取决于字段、字段值和日历系统。此外,在重新计算字段后,get(f)不一定返回值。具体内容由具体的日历类决定。
示例:考虑GregorianCalendar最初设置为1999年8月31日。调用set(Calendar.MONTH, Calendar.SEPTEMBER)将日历设置为1999年9月31日。这是一个临时内部表示,如果随后调用getTime(),则解析为1999年10月1日。但是,在调用getTime()之前调用set(Calendar.DAY\u OF_MONTH,30)会将日历设置为1999年9月30日,因为set()本身之后不会重新计算。
add(f,delta)将delta添加到字段f。这相当于调用set(f, get(f) + delta),并进行两次调整:
添加规则1。调用后字段f的值减去调用前字段f的值为delta,以字段f中发生的任何溢出为模。当字段值超出其范围时,会发生溢出,因此,下一个较大的字段会递增或递减,并且字段值会调整回其范围。
添加规则2。如果预期较小的字段是不变的,但由于字段f改变后其最小值或最大值的变化,该字段不可能等于其先前的值,则将其值调整为尽可能接近其预期值。较小的字段表示较小的时间单位。小时是一个比月中的天小的字段。不会对预计不会保持不变的较小字段进行调整。日历系统确定哪些字段应保持不变。
此外,与set()不同,add()强制立即重新计算日历的毫秒数和所有字段。
示例:考虑GregorianCalendar最初设置为1999年8月31日。调用add(Calendar.MONTH,13)将日历设置为2000年9月30日。添加规则1将月份字段设置为9月,因为将13个月添加到8月会得到下一年的9月。由于公历月份中的日期不能是9月31日,因此添加规则2会将月份中的日期设置为30,这是最接近的可能值。虽然它是一个较小的字段,但“周中的天”不受规则2的调整,因为当月份在GregoriaCalendar中发生变化时,它会发生变化。
滚动(f,增量)将增量添加到字段f,而不更改较大的字段。这相当于调用add(f,delta)并进行以下调整:
滚尺。较大的字段在调用后保持不变。较大的字段表示较大的时间单位。月的日比小时更大。
示例:考虑GregorianCalendar最初设置为1999年8月31日。呼叫roll(Calendar.MONTH, 8)将日历设置为1999年4月30日。添加规则1将月份字段设置为四月。使用GregorianCalendar,月份的日期不能是4月份的31日。添加规则2将其设置为最接近的值30。最后,滚动规则保持1999年的年份字段值。
例子:考虑GregorianCalendar最初设置为星期日1999年6月6日。通话记录(Calendar.WEEK\u OF_MONTH,-1)将日历设置为1999年6月1日星期二,而通话添加(Calendar.WEEK\u OF_MONTH,-1)将日历设置为1999年5月30日星期日。这是因为滚动规则施加了一个额外的约束:滚动月中的周时,月份不得更改。加上add规则1,结果日期必须介于6月1日星期二和6月5日星期六之间。根据add规则2,更改月的周时不变的周的日设置为星期二,这是与星期日最接近的值(其中星期日是一周的第一天)。
使用模型。为了激发Ad()和Reland()的行为,考虑一个用户界面组件,它包含月份、日和年的递增和递减按钮,以及底层GRGGORICANALDENAR。如果界面显示为1999年1月31日,并且用户按下月增量按钮,那么它应该显示什么?如果底层实现使用set(),则可能是1999年3月3日。一个更好的结果是1999年2月28日。此外,如果用户再次按下月增量按钮,则应显示为1999年3月31日,而不是1999年3月28日。通过保存原始日期并使用add()或roll(),取决于是否应该影响较大的字段,用户界面可以像大多数用户直观地期望的那样工作。
注意:您应该始终使用roll和add,而不是试图直接在日历的字段上执行算术运算。日历子类很可能具有具有非线性行为的字段,例如在非闰年期间缺少月份或天数。子类的add和roll方法将考虑到这一点,而简单的算术操作可能会给出无效的结果。

代码示例

代码示例来源:origin: stackoverflow.com

String dt = "2008-01-01";  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1);  // number of days to add
dt = sdf.format(c.getTime());  // dt is now the new date

代码示例来源:origin: ch.qos.logback/logback-classic

String computeTimeStampString(long now) {
    synchronized (this) {
      // Since the formatted output is only precise to the second, we can use the same cached string if the
      // current
      // second is the same (stripping off the milliseconds).
      if ((now / 1000) != lastTimestamp) {
        lastTimestamp = now / 1000;
        Date nowDate = new Date(now);
        calendar.setTime(nowDate);
        timesmapStr = String.format("%s %2d %s", simpleMonthFormat.format(nowDate), calendar.get(Calendar.DAY_OF_MONTH),
                simpleTimeFormat.format(nowDate));
      }
      return timesmapStr;
    }
  }
}

代码示例来源:origin: stackoverflow.com

Calendar c = Calendar.getInstance();
c.setTime(new Date(yourmilliseconds));
c.set(Calendar.MILLISECOND, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm.ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(c.getTime()));

代码示例来源:origin: spring-projects/spring-framework

@Override
  public Calendar convert(Long source) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(source);
    return calendar;
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
  public Calendar convert(Date source) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(source);
    return calendar;
  }
}

代码示例来源:origin: stackoverflow.com

import java.util.Calendar

Calendar c = Calendar.getInstance(); 
int seconds = c.get(Calendar.SECOND);

代码示例来源:origin: NanoHttpd/nanohttpd

public static String getHTTPTime(int days) {
  Calendar calendar = Calendar.getInstance();
  SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
  dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
  calendar.add(Calendar.DAY_OF_MONTH, days);
  return dateFormat.format(calendar.getTime());
}

代码示例来源:origin: ctripcorp/apollo

private static Date getDayBeginTime(Date date) {
 Calendar calendar = Calendar.getInstance();
 calendar.setTime(date);
 calendar.set(Calendar.HOUR, 0);
 calendar.set(Calendar.MINUTE, 0);
 calendar.set(Calendar.SECOND, 0);
 calendar.set(Calendar.MILLISECOND, 0);
 return new Date(calendar.getTime().getTime());
}

代码示例来源:origin: ctripcorp/apollo

public static Date getDateOffset(int offset) {
 Calendar calendar = Calendar.getInstance();
 calendar.setTime(new Date());
 calendar.add(calendar.DATE, offset);
 return getDayBeginTime(calendar.getTime());
}

代码示例来源:origin: north2016/T-MVP

public static List<String> getOldWeekDays() {
  final Calendar c = Calendar.getInstance();
  String[] months = new String[8];
  for (int i = 0; i < 8; i++) {
    months[i] = new SimpleDateFormat("MM.dd").format(new Date(c
        .getTimeInMillis()));
    c.add(Calendar.DAY_OF_MONTH, -1);
  }
  return Arrays.asList(months);
}

代码示例来源:origin: AsyncHttpClient/async-http-client

/**
 * Sets the Date and Cache headers for the HTTP Response
 *
 * @param response    HTTP response
 * @param fileToCache file to extract content type
 */
private static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
 SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
 dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
 // Date header
 Calendar time = new GregorianCalendar();
 response.headers().set(DATE, dateFormatter.format(time.getTime()));
 // Add cache headers
 time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
 response.headers().set(EXPIRES, dateFormatter.format(time.getTime()));
 response.headers().set(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
 response.headers().set(
     LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
}

代码示例来源:origin: knowm/XChange

public static Long toEpoch(Date dateTime, String timeZone) {
 // Epoch of midnight in local time zone
 Calendar timeOffset = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
 timeOffset.set(Calendar.MILLISECOND, 0);
 timeOffset.set(Calendar.SECOND, 0);
 timeOffset.set(Calendar.MINUTE, 0);
 timeOffset.set(Calendar.HOUR_OF_DAY, 0);
 long midnightOffSet = timeOffset.getTime().getTime();
 long localTimestamp = dateTime.getTime();
 return timeOffset == null ? null : midnightOffSet + localTimestamp;
}

代码示例来源:origin: elastic/elasticsearch-hadoop

@Test
public void testCalendar() {
  Date d = new Date(0);
  Calendar cal = Calendar.getInstance();
  cal.setTime(d);
  assertThat(jdkTypeToJson(cal), containsString(new SimpleDateFormat("yyyy-MM-dd").format(d)));
}

代码示例来源:origin: knowm/XChange

@Override
 public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
  final String dateTimeInUnixFormat = p.getText();
  try {
   Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
   calendar.setTimeInMillis(Long.parseLong(dateTimeInUnixFormat + "000"));
   return calendar.getTime();
  } catch (Exception e) {
   return new Date(0);
  }
 }
}

代码示例来源:origin: stackoverflow.com

Calendar c = Calendar.getInstance();
 System.out.println("current: "+c.getTime());
 TimeZone z = c.getTimeZone();
 int offset = z.getRawOffset();
 if(z.inDaylightTime(new Date())){
   offset = offset + z.getDSTSavings();
 }
 int offsetHrs = offset / 1000 / 60 / 60;
 int offsetMins = offset / 1000 / 60 % 60;
 System.out.println("offset: " + offsetHrs);
 System.out.println("offset: " + offsetMins);
 c.add(Calendar.HOUR_OF_DAY, (-offsetHrs));
 c.add(Calendar.MINUTE, (-offsetMins));
 System.out.println("GMT Time: "+c.getTime());

代码示例来源:origin: stackoverflow.com

TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat = 
    new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);

System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();

System.out.println("UTC:     " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());

代码示例来源:origin: square/moshi

private Date newDate(int year, int month, int day, int hour, int offset) {
  Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
  calendar.set(year, month - 1, day, hour, 0, 0);
  calendar.set(Calendar.MILLISECOND, 0);
  return new Date(calendar.getTimeInMillis() - TimeUnit.HOURS.toMillis(offset));
 }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testSetParameterValueWithDateAndCalendar() throws SQLException {
  java.util.Calendar cal = new GregorianCalendar();
  StatementCreatorUtils.setParameterValue(preparedStatement, 1, Types.DATE, null, cal);
  verify(preparedStatement).setDate(1, new java.sql.Date(cal.getTime().getTime()), cal);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testIncrementSecondWithPreviousExecutionTooEarly() throws Exception {
  CronTrigger trigger = new CronTrigger("11 * * * * *", timeZone);
  calendar.set(Calendar.SECOND, 11);
  SimpleTriggerContext context = new SimpleTriggerContext();
  context.update(calendar.getTime(), new Date(calendar.getTimeInMillis() - 100),
      new Date(calendar.getTimeInMillis() - 90));
  calendar.add(Calendar.MINUTE, 1);
  assertEquals(calendar.getTime(), trigger.nextExecutionTime(context));
}

代码示例来源:origin: ctripcorp/apollo

private Calendar calExpiredTime() {
 Calendar calendar = Calendar.getInstance();
 calendar.setTime(DateUtils.addHours(new Date(), portalConfig.survivalDuration()));
 return calendar;
}

相关文章

微信公众号

最新文章

更多