下面列出了java.util.Calendar#after ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public int getNumberOfBusinessDaysBetween(final Calendar d1, final Calendar d2) {
if (d1 == null || d2 == null) {
return 0;
}
final boolean d1B4d2 = !d1.after(d2);
Calendar start = d1B4d2 ? d1 : d2;
final Calendar end = d1B4d2 ? d2 : d1;
if (getHolidayHandler() != null) {
start = getHolidayHandler().adjustDate(start, 1, this);
}
int count = 0;
while (start.before(end)) {
if (!isNonWorkingDay(start)) {
count++;
}
start.add(Calendar.DATE, 1);
}
return d1B4d2 ? count : -count;
}
public static String formatCommitDate(long value) {
Calendar today = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(value);
if (cal.after(today))
return "In future";
int seconds = getDifference(today, cal, Calendar.SECOND, 60);
if (seconds < 60)
return timeText(seconds, "second");
int minutes = getDifference(today, cal, Calendar.MINUTE, 60);
if (minutes < 60)
return timeText(minutes, "minute");
int hours = getDifference(today, cal, Calendar.HOUR_OF_DAY, 24);
if (hours < 24)
return timeText(hours, "hour");
int days = getDifference(today, cal, Calendar.DAY_OF_MONTH, 365);
if (days < 7)
return timeText(days, "day");
if (days < 31)
return timeText(days / 7, "week");
int months = getDifference(today, cal, Calendar.MONTH, 12);
if (days < 365 && months > 0)
return timeText(months, "month");
int years = Calendar.getInstance().get(Calendar.YEAR) - cal.get(Calendar.YEAR);
return timeText(years, "year");
}
@Override
public void updateViews(Context context, int appWidgetId, RemoteViews views, SuntimesRiseSetData data)
{
super.updateViews(context, appWidgetId, views, data);
boolean showSeconds = WidgetSettings.loadShowSecondsPref(context, appWidgetId);
WidgetSettings.RiseSetOrder order = WidgetSettings.loadRiseSetOrderPref(context, appWidgetId);
Calendar event = data.sunriseCalendar(1);
if (order != WidgetSettings.RiseSetOrder.TODAY)
{
Calendar now = Calendar.getInstance();
if (now.after(event)) {
event = data.sunriseCalendar(2);
}
}
updateViewsSunriseText(context, views, event, showSeconds);
}
/**
* {@inheritDoc}
*/
public boolean isModified() {
if (!isUnwrapped()) {
return false;
}
Calendar mod = getLastModified();
if (mod == null) {
return false;
}
Calendar uw = getLastWrapped();
if (uw == null) {
uw = getLastUnwrapped();
}
if (uw == null) {
// backward compat check
try {
if (defNode.hasProperty("unwrapped")) {
return true;
}
} catch (RepositoryException e) {
log.warn("Error while checking unwrapped property", e);
}
return false;
}
return mod.after(uw);
}
/**
* This returns true is the rule is effective.
* If the rule is not effective, it cannot activate.
*
* This uses the dateEffective, dateExpires and enabled flag to decide this.
*/
public boolean isEffective(Tuple tuple,
RuleTerminalNode rtn,
WorkingMemory workingMemory) {
if ( !this.enabled.getValue( tuple,
rtn.getEnabledDeclarations(),
this,
workingMemory ) ) {
return false;
}
if ( this.dateEffective == null && this.dateExpires == null ) {
return true;
} else {
Calendar now = Calendar.getInstance();
now.setTimeInMillis( workingMemory.getSessionClock().getCurrentTime() );
if ( this.dateEffective != null && this.dateExpires != null ) {
return (now.after( this.dateEffective ) && now.before( this.dateExpires ));
} else if ( this.dateEffective != null ) {
return (now.after( this.dateEffective ));
} else {
return (now.before( this.dateExpires ));
}
}
}
/**
* Applies the config to the given calendar.
*/
public static Calendar applyConfig(Calendar cal, AstroChannelConfig config) {
Calendar cCal = cal;
if (config.getOffset() != null && config.getOffset() != 0) {
Calendar cOffset = Calendar.getInstance();
cOffset.setTime(cCal.getTime());
cOffset.add(Calendar.MINUTE, config.getOffset());
cCal = cOffset;
}
Calendar cEarliest = adjustTime(cCal, getMinutesFromTime(config.getEarliest()));
if (cCal.before(cEarliest)) {
return cEarliest;
}
Calendar cLatest = adjustTime(cCal, getMinutesFromTime(config.getLatest()));
if (cCal.after(cLatest)) {
return cLatest;
}
return cCal;
}
private Calendar getEarlierCalendar(Calendar dayOfMonthCalendar, Calendar dayOfWeekCalendar) throws Exception {
Calendar withDayOfMonth = fillOutCalendar(dayOfMonthCalendar);
if (LOG.isDebugEnabled()) {
LOG.debug("dayOfMonthCalendar:[" + (withDayOfMonth != null ? withDayOfMonth.getTime() : null) + "]");
}
Calendar withDayOfWeek = fillOutCalendar(dayOfWeekCalendar);
if (LOG.isDebugEnabled()) {
LOG.debug("dayOfWeekCalendar:[" + (withDayOfWeek != null ? withDayOfWeek.getTime() : null) + "]");
}
if (withDayOfMonth != null && withDayOfWeek != null) {
return withDayOfMonth.after(withDayOfWeek) ? withDayOfMonth : withDayOfWeek;
} else if (withDayOfMonth == null) {
return withDayOfWeek;
} else {
return withDayOfMonth;
}
}
public void showGuide() {
hide();
mPlaybackController.mVideoManager.contractVideo(Utils.convertDpToPixel(mActivity, 300));
mTvGuide.setVisibility(View.VISIBLE);
mGuideVisible = true;
Calendar now = Calendar.getInstance();
boolean needLoad = mCurrentGuideStart == null;
if (!needLoad) {
Calendar needLoadTime = (Calendar) mCurrentGuideStart.clone();
needLoadTime.add(Calendar.MINUTE, 30);
needLoad = now.after(needLoadTime);
}
if (needLoad) {
loadGuide();
}
}
/**
* @param calendar a datetime
* @param latitude the latitude of the location in degrees.
* @param longitude the longitude of the location in degrees (West is negative)
* @return true if it is night at the given location and datetime. This returns
* true if the given datetime at the location is after the astronomical twilight dusk and before
* the astronomical twilight dawn.
*/
public static boolean isNight(Calendar calendar, double latitude, double longitude) {
Calendar[] astronomicalTwilight = getAstronomicalTwilight(calendar, latitude, longitude);
if (astronomicalTwilight == null) {
int month = calendar.get(Calendar.MONTH); // Reminder: January = 0
if (latitude > 0) {
if (month >= 3 && month <= 10) {
return false; // Always day at the north pole in June
} else {
return true; // Always night at the north pole in December
}
} else {
if (month >= 3 && month <= 10) {
return true; // Always night at the south pole in June
} else {
return false; // Always day at the south pole in December
}
}
}
Calendar dawn = astronomicalTwilight[0];
Calendar dusk = astronomicalTwilight[1];
@SuppressLint("SimpleDateFormat")
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
format.setTimeZone(calendar.getTimeZone());
return calendar.before(dawn) || calendar.after(dusk);
}
/**
* @param calendar the datetime for which to determine if it's nautical twilight in the given location
* @param latitude the latitude of the location in degrees.
* @param longitude the longitude of the location in degrees (West is negative)
* @return true if it is nautical twilight at the given location and the given calendar.
* This returns true if the given time at the location is between civil and nautical twilight dusk
* or between nautical and civil twilight dawn.
*/
public static boolean isNauticalTwilight(Calendar calendar, double latitude, double longitude) {
Calendar[] civilTwilight = getCivilTwilight(calendar, latitude, longitude);
if (civilTwilight == null) return false;
Calendar[] nauticalTwilight = getNauticalTwilight(calendar, latitude, longitude);
if (nauticalTwilight == null) return false;
return (calendar.after(civilTwilight[1]) && calendar.before(nauticalTwilight[1])
|| (calendar.after(nauticalTwilight[0]) && calendar.before(civilTwilight[0])));
}
public Transition nextTransition(Calendar from) {
for(Transition transition : transitions()) {
Calendar c = CalendarUtil.setTime(from, transition.timeOfDay());
if(c.after(from)) {
return Transition.builder(transition).withStartTime(c.getTime()).build();
}
}
return null;
}
private Calendar getDateAfterRepeat(Calendar date) {
Calendar current = TimeZoneUtil.convertToTimeZone(start, date.getTimeZone());
if (repeatWithNoBounds) {
while(current.before(date) || current.equals(date)) { // As long as current date is not past the engine date, we keep looping
Calendar newTime = add(current, period);
if (newTime.equals(current) || newTime.before(current)) {
break;
}
current = newTime;
}
} else {
int maxLoops = times;
if (maxIterations > 0) {
maxLoops = maxIterations - times;
}
for (int i = 0; i < maxLoops+1 && !current.after(date); i++) {
current = add(current, period);
}
}
return current.before(date) ? date : TimeZoneUtil.convertToTimeZone(current, clockReader.getCurrentTimeZone());
}
private Calendar getDateAfterRepeat(Calendar date) {
Calendar current = TimeZoneUtil.convertToTimeZone(start, date.getTimeZone());
if (repeatWithNoBounds) {
while (current.before(date) || current.equals(date)) { // As long as current date is not past the engine date, we keep looping
Calendar newTime = add(current, period);
if (newTime.equals(current) || newTime.before(current)) {
break;
}
current = newTime;
}
} else {
int maxLoops = times;
if (maxIterations > 0) {
maxLoops = maxIterations - times;
}
for (int i = 0; i < maxLoops + 1 && !current.after(date); i++) {
current = add(current, period);
}
}
return current.before(date) ? date : TimeZoneUtil.convertToTimeZone(current, clockReader.getCurrentTimeZone());
}
/**
* @param calendar the datetime for which to determine if it's civil twilight in the given location
* @param latitude the latitude of the location in degrees.
* @param longitude the longitude of the location in degrees (West is negative)
* @return true if it is civil twilight at the given location and the given calendar.
* This returns true if the given time at the location is between sunset and civil twilight dusk
* or between civil twilight dawn and sunrise.
*/
public static boolean isCivilTwilight(Calendar calendar, double latitude, double longitude) {
Calendar[] sunriseSunset = getSunriseSunset(calendar, latitude, longitude);
if (sunriseSunset == null) return false;
Calendar[] civilTwilight = getCivilTwilight(calendar, latitude, longitude);
if (civilTwilight == null) return false;
return (calendar.after(sunriseSunset[1]) && calendar.before(civilTwilight[1])
|| (calendar.after(civilTwilight[0]) && calendar.before(sunriseSunset[0])));
}
public void updateField(Context context, Calendar now, Calendar dateTime, boolean showWeeks, boolean showTime, boolean showHours, boolean showSeconds)
{
if (field != null)
{
field.setText(utils.calendarDateTimeDisplayString(context, dateTime, showTime, showSeconds).getValue());
}
if (note != null)
{
String noteText = (dateTime == null ? "" : utils.timeDeltaDisplayString(now.getTime(), dateTime.getTime(), showWeeks, showHours).toString());
String noteString = now.after(dateTime) ? context.getString(R.string.ago, noteText) : context.getString(R.string.hence, noteText);
note.setText(SuntimesUtils.createBoldColorSpan(null, noteString, noteText, noteColor));
note.setVisibility(View.VISIBLE);
}
}
@Override
public void run() {
Calendar cal = EventTimer.getCalendarInServerTimeZone();
for (EventTimer timer : EventTimer.timers.values()) {
if (cal.after(timer.getNext())) {
timer.setLast(cal);
Calendar next;
try {
next = timer.getEventFunction().getNextDate();
} catch (InvalidConfiguration e) {
e.printStackTrace();
continue;
}
if (next == null) {
CivLog.warning("WARNING timer:"+timer.getName()+" did not return a next time.");
continue;
}
timer.setNext(next);
timer.save();
timer.getEventFunction().process();
}
}
}
/**
* 建议改名, 实现有错 判断时间1是否在时间2之前.
* @param date1
* String 类型的时间1 格式为"yyyy-mm-dd"
* @param date2
* String 类型的时间1 格式为"yyyy-mm-dd"
* @return boolean
* ture: date2 > date 1; false: date2 <= date1
*/
public static boolean getCompareResult(String date1, String date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(strToDate(date1));
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(strToDate(date2));
if (calendar2.after(calendar1)) {
return true;
}
return false;
}
public static String formatDateDiff(Calendar fromDate, Calendar toDate, int maxacc, @Nullable Integer disable) {
boolean future = false;
if (toDate.equals(fromDate)) {
return Messages.getColored("core.time.now");
}
if (toDate.after(fromDate)) {
future = true;
}
StringBuilder sb = new StringBuilder();
int[] types = {1, 2, 5, 11, 12, 13};
String[] names = {
Messages.getColored("core.time.years"),
Messages.getColored("core.time.year"),
Messages.getColored("core.time.months"),
Messages.getColored("core.time.month"),
Messages.getColored("core.time.days"),
Messages.getColored("core.time.day"),
Messages.getColored("core.time.hours"),
Messages.getColored("core.time.hour"),
Messages.getColored("core.time.minutes"),
Messages.getColored("core.time.minute"),
Messages.getColored("core.time.seconds"),
Messages.getColored("core.time.second")
};
int accuracy = 0;
for (int i = 0; i < types.length; i++) {
if (accuracy >= maxacc) {
break;
}
int diff = dateDiff(types[i], fromDate, toDate, future);
if (diff > 0) {
accuracy++;
int name = ((i * 2) + (diff == 1 ? 1 : 0));
if (disable != null && name >= disable) {
continue;
}
sb.append(" ").append(diff).append(" ").append(names[name]);
}
}
if (sb.length() == 0) {
return Messages.getColored("core.time.now");
}
return sb.toString().trim();
}
/***
* Generate a random scheduled time between specified execution time window in the Azkaban compatible format
* which is: hh,mm,a,z Eg. ScheduleTime=12,00,PM,PDT
*
* @param windowStartHour Window start hour in 24 hr (HH) format (inclusive)
* @param windowEndHour Window end hour in 24 hr (HH) format (exclusive)
* @param delayMinutes If current time is within window, then additional delay for bootstrapping if desired
* @return Scheduled time string of the format hh,mm,a,z
*/
@edu.umd.cs.findbugs.annotations.SuppressWarnings(
value = "DMI_RANDOM_USED_ONLY_ONCE",
justification = "As expected for randomization")
public static String getScheduledTimeInAzkabanFormat(int windowStartHour, int windowEndHour, int delayMinutes) {
// Validate
if (windowStartHour < 0 || windowEndHour > 23 || windowStartHour >= windowEndHour) {
throw new IllegalArgumentException("Window start should be less than window end, and both should be between "
+ "0 and 23");
}
if (delayMinutes < 0 || delayMinutes > 59) {
throw new IllegalArgumentException("Delay in minutes should be between 0 and 59 (inclusive)");
}
// Setup window
Calendar windowStartTime = Calendar.getInstance();
windowStartTime.set(Calendar.HOUR_OF_DAY, windowStartHour);
windowStartTime.set(Calendar.MINUTE, 0);
windowStartTime.set(Calendar.SECOND, 0);
Calendar windowEndTime = Calendar.getInstance();
windowEndTime.set(Calendar.HOUR_OF_DAY, windowEndHour);
windowEndTime.set(Calendar.MINUTE, 0);
windowEndTime.set(Calendar.SECOND, 0);
// Check if current time is between windowStartTime and windowEndTime, then let the execution happen
// after delayMinutes minutes
Calendar now = Calendar.getInstance();
if (now.after(windowStartTime) && now.before(windowEndTime)) {
// Azkaban takes a few seconds / a minute to bootstrap,
// so extra few minutes get the first execution to run instantly
now.add(Calendar.MINUTE, delayMinutes);
return new SimpleDateFormat("hh,mm,a,z").format(now.getTime());
}
// Current time is not between windowStartTime and windowEndTime, so get random execution time for next day
int allowedSchedulingWindow = (int)((windowEndTime.getTimeInMillis() - windowStartTime.getTimeInMillis()) /
MILLISECONDS_IN_HOUR);
int randomHourInWindow = new Random(System.currentTimeMillis()).nextInt(allowedSchedulingWindow);
int randomMinute = new Random(System.currentTimeMillis()).nextInt(60);
windowStartTime.add(Calendar.HOUR, randomHourInWindow);
windowStartTime.set(Calendar.MINUTE, randomMinute);
return new SimpleDateFormat("hh,mm,a,z").format(windowStartTime.getTime());
}
private PropertyChangeListener chechkDates() {
final PropertyChangeListener listener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
// here leave ancestors empty because we need dates not ancestor
if (evt.getPropertyName().equals("ancestor")) {
return;
}
boolean showed = false;
startDate = checkinDateChooser.getDate();
endDate = checkoutDateChooser.getDate();
if (startDate != null && endDate != null) {
// add to calendar to be able get day of date
// and compare
Calendar cs = Calendar.getInstance();
cs.setTime(startDate);
Calendar ce = Calendar.getInstance();
ce.setTime(endDate);
// compare if start date greater than end date
if (cs.after(ce) && !showed) {
JOptionPane.showMessageDialog(null, "Start date is after end date!",
JOptionPane.MESSAGE_PROPERTY, JOptionPane.WARNING_MESSAGE);
showed = true;
}
// or both is same date
else if (cs.get(Calendar.DAY_OF_YEAR) == ce.get(Calendar.DAY_OF_YEAR) && !showed) {
JOptionPane.showMessageDialog(null,
"Start date equals end date!\nPlease be sure you're choose right date.",
JOptionPane.MESSAGE_PROPERTY, JOptionPane.WARNING_MESSAGE);
showed = true;
}
// other odds
else {
value = (int) ((startDate.getTime() - endDate.getTime()) / (1000 * 60 * 60 * 24));
totalDaysField.setText(Math.abs(value) + "");
totalDaysField.revalidate();
totalDaysField.repaint();
}
}
}
};
return listener;
}