下面列出了java.util.Calendar#setLenient ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Construct a DateTime object representing a date and time, with an explicit timezone.
*
* @param year The year of the datetime
* @param month The month of the datetime
* @param day The day of the datetime
* @param hour The hour of the datetime
* @param minute The minute of the datetime
* @param second The second of the datetime
* @param millisecond The millisecond of the datetime
* @param hourOffset The timezone offset of the time, in hours
* @param minuteOffset The timezone offset of the time, in minutes
*/
private DateTimeValue(int year, int month, int day, int hour, int minute, int second, int millisecond, int hourOffset, int minuteOffset) {
super();
this.year = year;
this.month = month;
this.day = day;
this.hour = hour;
this.minute = minute;
this.second = second;
this.millisecond = millisecond;
this.timezoneHours = hourOffset;
this.timezoneMinutes = minuteOffset;
// Check to make sure the provided values are valid.
// TODO: Failure here should throw a PDB exception.
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(TimeValue.getTZString(hourOffset,minuteOffset)),Locale.getDefault());
cal.setLenient(false);
cal.set(year, month-1, day, hour, minute, second);
cal.set(Calendar.MILLISECOND, millisecond);
try {
cal.get(Calendar.HOUR_OF_DAY);
} catch (IllegalArgumentException iae) {
throw new InvalidDateTimeException("Cannot create datetime with provided values.");
}
}
/**
* Tests a full ISO datetime string.
*/
public void testNormalConvertFromIsoDateTimeString()
{
String textRep = "2004-01-13 04:45:09.245";
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.clear();
cal.set(Calendar.HOUR, 4);
cal.set(Calendar.MINUTE, 45);
cal.set(Calendar.SECOND, 9);
Object result = _timeConverter.convertFromString(textRep, Types.TIME);
assertTrue(result instanceof Time);
assertEquals(cal.getTimeInMillis(), ((Time)result).getTime());
}
/**
* Construct a DateTime object representing a time with an explicit timezone offset.
*
* @param hour The hour of the time
* @param minute The minute of the time
* @param second The second of the time
* @param millisecond The millisecond of the time
* @param hourOffset The timezone offset of the time, in hours
* @param minuteOffset The timezone offset of the time, in minutes
*/
private TimeValue(int hour, int minute, int second, int millisecond, int hourOffset, int minuteOffset) {
super();
this.hour = hour;
this.minute = minute;
this.second = second;
this.millisecond = millisecond;
this.timezoneHours = hourOffset;
this.timezoneMinutes = minuteOffset;
// Check to make sure the provided values are valid.
// TODO: Failure here should throw a PDB exception.
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(getTZString(hourOffset,minuteOffset)),Locale.getDefault());
cal.setLenient(false);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
cal.set(Calendar.MILLISECOND, millisecond);
try {
cal.get(Calendar.HOUR_OF_DAY);
} catch (IllegalArgumentException iae) {
throw new InvalidDateTimeException("Cannot create time with provided values.");
}
}
@Test
public void testTimer() {
Scheduler scheduler = Scheduler.create(vertx);
final Calendar target = Calendar.getInstance();
target.setLenient(true);
final Logger log = container.logger();
log.info("Starting timer test at " + target.getTime().toString());
target.add(Calendar.SECOND, 30);
log.info("Waiting for callback at " + target.getTime().toString());
scheduler.setTimer(getTimeOfWeek(target), new Handler<Timer>() {
public void handle(Timer t) {
assertTrue(closeEnough(target, Calendar.getInstance()));
assertTrue(t.getNext() == null);
testComplete();
}
});
}
/**
* <p>
* Get a <code>Date</code> object that represents the given time, on
* tomorrow's date.
* </p>
*
* @param second
* The value (0-59) to give the seconds field of the date
* @param minute
* The value (0-59) to give the minutes field of the date
* @param hour
* The value (0-23) to give the hours field of the date
* @return the new date
*/
public static Date tomorrowAt(int hour, int minute, int second) {
validateSecond(second);
validateMinute(minute);
validateHour(hour);
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.setLenient(true);
// advance one day
c.add(Calendar.DAY_OF_YEAR, 1);
c.set(Calendar.HOUR_OF_DAY, hour);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, second);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
}
public static Date addMonths(Date date, int monthsCount) {
if (date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setLenient(false);
calendar.add(Calendar.MONTH, monthsCount);
return calendar.getTime();
}
/**
* Parse the input string and return the corresponding calendar field
* number.
*/
private static double getNumber(String in, String[] formats, int calField)
throws ParseException
{
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
// Try the allowed formats, from longest to shortest.
Date date = testFormats(in, formats);
if (date == null) return Double.NaN;
cal.setTime(date);
return cal.get(calField);
}
/**
* 年を取得します。
* @param date 基準となる日付
* @return 年
*/
public static int getYear(Date date) {
if (date == null) return -1;
Calendar calendar = Calendar.getInstance();
calendar.setLenient(true);
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
/**
* 前の年を求めます。
* @param date 基準となる日付
* @return 新しい日付
*/
public static Date previousYear(Date date) {
if (date == null) return null;
Calendar calendar = Calendar.getInstance();
calendar.setLenient(true);
calendar.setTime(date);
calendar.add(Calendar.YEAR, -1);
return calendar.getTime();
}
/**
* It will save the SignupMeeting list into DB and send email to notify
* participants
*
* @throws Exception
*/
public void processSaveMeetings() throws Exception
{
Calendar calendar = Calendar.getInstance();
int numOfRecurs = 0;// once Only
/* For recurrence case */
if (!ONCE_ONLY.equals(signupMeeting.getRepeatType())) {
numOfRecurs = signupMeeting.getRepeatNum();
//getNumOfRecurrence(signupMeeting.getRepeatType(), signupMeeting.getStartTime(), signupMeeting.getRepeatUntil());
}
calendar.setLenient(true);
calendar.setTime(signupMeeting.getStartTime());
// recurrence = true;
if (DAILY.equals(signupMeeting.getRepeatType())) {
createRecurMeetings(calendar, numOfRecurs, perDay);
} else if (WEEKDAYS.equals(signupMeeting.getRepeatType())) {
createRecurMeetings(calendar, numOfRecurs, perDay);
removeWeekendDays();
}else if (WEEKLY.equals(signupMeeting.getRepeatType())) {
createRecurMeetings(calendar, numOfRecurs, perWeek);
} else if (BIWEEKLY.equals(signupMeeting.getRepeatType())) {
createRecurMeetings(calendar, numOfRecurs, perBiweek);
} else
createRecurMeetings(calendar, numOfRecurs, onceOnly);
postMeetings(signupMeetings);
}
protected Date parse(String dateString, String pattern) throws ParseException {
if (!StringUtils.isBlank(dateString)) {
DateFormat dateFormat = new SimpleDateFormat(pattern);
dateFormat.setLenient(false);
ParsePosition parsePosition = new ParsePosition(0);
Date testDate = dateFormat.parse(dateString, parsePosition);
// Ensure that the entire date String can be parsed by the current format.
if (testDate == null) {
throw new ParseException("The date that you provided is invalid.",parsePosition.getErrorIndex());
} else if (parsePosition.getIndex() != dateString.length()) {
throw new ParseException("The date that you provided is invalid.",parsePosition.getIndex());
}
// Ensure that the date's year lies between 1000 and 9999, to help prevent database-related date errors.
Calendar testCalendar = Calendar.getInstance();
testCalendar.setLenient(false);
testCalendar.setTime(testDate);
if (testCalendar.get(Calendar.YEAR) < 1000 || testCalendar.get(Calendar.YEAR) > 9999) {
throw new ParseException("The date that you provided is not between the years 1000 and 9999.",-1);
}
if(testCalendar.get(Calendar.YEAR) == 1970 && !pattern.contains("y".toLowerCase())){
Calendar curCalendar = Calendar.getInstance();
curCalendar.setTime(new java.util.Date());
testCalendar.set(Calendar.YEAR, curCalendar.get(Calendar.YEAR));
testDate = testCalendar.getTime();
}
return testDate;
}
return null;
}
/**
* Tests converting a normal date to a string.
*/
public void testNormalConvertToString()
{
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.clear();
cal.set(2005, 11, 19);
Date date = new Date(cal.getTimeInMillis());
String result = _dateConverter.convertToString(date, Types.DATE);
assertNotNull(result);
assertEquals("2005-12-19", result);
}
private static Calendar getCalendar()
{
// don't need to synchronize, it's harmless if we have 2 instances
// and we synchronize on class anyway
if (c == null) {
final Calendar calendar = Calendar.getInstance();
calendar.setLenient(false);
c = calendar;
}
return c;
}
public int getDay(int week, int dayOfWeek) {
Calendar c = Calendar.getInstance(Locale.US);
c.setTime(iForm.getSessionBeginDate());
c.setLenient(true);
c.add(Calendar.WEEK_OF_YEAR, week-1);
c.add(Calendar.DAY_OF_WEEK, dayOfWeek - c.get(Calendar.DAY_OF_WEEK));
Calendar ec = Calendar.getInstance(Locale.US);
ec.setTime(iForm.getExamBeginDate());
return c.get(Calendar.DAY_OF_YEAR)-ec.get(Calendar.DAY_OF_YEAR);
}
public int getDayOfWeek(int day) {
Calendar cal = Calendar.getInstance(Locale.US);
cal.setTime(iForm.getExamBeginDate());
cal.setLenient(true);
cal.add(Calendar.DAY_OF_YEAR, day);
return cal.get(Calendar.DAY_OF_WEEK);
}
/**
* <p>
* Returns the final time at which the <code>DateIntervalTrigger</code> will
* fire, if there is no end time set, null will be returned.
* </p>
*
* <p>
* Note that the return time may be in the past.
* </p>
*/
public Date getFinalFireTime() {
if (complete || getEndTime() == null) {
return null;
}
// back up a second from end time
Date fTime = new Date(getEndTime().getTime() - 1000L);
// find the next fire time after that
fTime = getFireTimeAfter(fTime, true);
// the the trigger fires at the end time, that's it!
if(fTime.equals(getEndTime()))
return fTime;
// otherwise we have to back up one interval from the fire time after the end time
Calendar lTime = Calendar.getInstance();
lTime.setTime(fTime);
lTime.setLenient(true);
if(getRepeatIntervalUnit().equals(IntervalUnit.SECOND)) {
lTime.add(java.util.Calendar.SECOND, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.MINUTE)) {
lTime.add(java.util.Calendar.MINUTE, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.HOUR)) {
lTime.add(java.util.Calendar.HOUR_OF_DAY, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.DAY)) {
lTime.add(java.util.Calendar.DAY_OF_YEAR, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.WEEK)) {
lTime.add(java.util.Calendar.WEEK_OF_YEAR, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.MONTH)) {
lTime.add(java.util.Calendar.MONTH, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.YEAR)) {
lTime.add(java.util.Calendar.YEAR, -1 * getRepeatInterval());
}
return lTime.getTime();
}
/**
* Calendar and GregorianCalendar hashCode() methods need improvement.
* Calendar needs a good implementation that subclasses can override,
* and GregorianCalendar should use that implementation.
*/
public void Test4136399() {
/* Note: This test is actually more strict than it has to be.
* Technically, there is no requirement that unequal objects have
* unequal hashes. We only require equal objects to have equal hashes.
* It is desirable for unequal objects to have distributed hashes, but
* there is no hard requirement here.
*
* In this test we make assumptions about certain attributes of calendar
* objects getting represented in the hash, which need not always be the
* case (although it does work currently with the given test). */
Calendar a = Calendar.getInstance();
Calendar b = (Calendar) a.clone();
if (a.hashCode() != b.hashCode()) {
errln("Calendar hash code unequal for cloned objects");
}
b.setMinimalDaysInFirstWeek(7 - a.getMinimalDaysInFirstWeek());
if (a.hashCode() == b.hashCode()) {
errln("Calendar hash code ignores minimal days in first week");
}
b.setMinimalDaysInFirstWeek(a.getMinimalDaysInFirstWeek());
b.setFirstDayOfWeek((a.getFirstDayOfWeek() % 7) + 1); // Next day
if (a.hashCode() == b.hashCode()) {
errln("Calendar hash code ignores first day of week");
}
b.setFirstDayOfWeek(a.getFirstDayOfWeek());
b.setLenient(!a.isLenient());
if (a.hashCode() == b.hashCode()) {
errln("Calendar hash code ignores lenient setting");
}
b.setLenient(a.isLenient());
// Assume getTimeZone() returns a reference, not a clone
// of a reference -- this is true as of this writing
b.getTimeZone().setRawOffset(a.getTimeZone().getRawOffset() + 60 * 60 * 1000);
if (a.hashCode() == b.hashCode()) {
errln("Calendar hash code ignores zone");
}
b.getTimeZone().setRawOffset(a.getTimeZone().getRawOffset());
GregorianCalendar c = new GregorianCalendar();
GregorianCalendar d = (GregorianCalendar) c.clone();
if (c.hashCode() != d.hashCode()) {
errln("GregorianCalendar hash code unequal for clones objects");
}
Date cutover = c.getGregorianChange();
d.setGregorianChange(new Date(cutover.getTime() + 24 * 60 * 60 * 1000));
if (c.hashCode() == d.hashCode()) {
errln("GregorianCalendar hash code ignores cutover");
}
}
/**
* <p>
* Returns the final time at which the <code>DateIntervalTrigger</code> will
* fire, if there is no end time set, null will be returned.
* </p>
*
* <p>
* Note that the return time may be in the past.
* </p>
*/
@Override
public Date getFinalFireTime() {
if (complete || getEndTime() == null) {
return null;
}
// back up a second from end time
Date fTime = new Date(getEndTime().getTime() - 1000L);
// find the next fire time after that
fTime = getFireTimeAfter(fTime, true);
// the the trigger fires at the end time, that's it!
if(fTime.equals(getEndTime()))
return fTime;
// otherwise we have to back up one interval from the fire time after the end time
Calendar lTime = Calendar.getInstance();
if(timeZone != null)
lTime.setTimeZone(timeZone);
lTime.setTime(fTime);
lTime.setLenient(true);
if(getRepeatIntervalUnit().equals(IntervalUnit.SECOND)) {
lTime.add(java.util.Calendar.SECOND, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.MINUTE)) {
lTime.add(java.util.Calendar.MINUTE, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.HOUR)) {
lTime.add(java.util.Calendar.HOUR_OF_DAY, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.DAY)) {
lTime.add(java.util.Calendar.DAY_OF_YEAR, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.WEEK)) {
lTime.add(java.util.Calendar.WEEK_OF_YEAR, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.MONTH)) {
lTime.add(java.util.Calendar.MONTH, -1 * getRepeatInterval());
}
else if(getRepeatIntervalUnit().equals(IntervalUnit.YEAR)) {
lTime.add(java.util.Calendar.YEAR, -1 * getRepeatInterval());
}
return lTime.getTime();
}
/**
* 指定された引数から、日付を作成します。
* @param year 年
* @param month 月
* @param day 日
* @param hourOfDay 時
* @param minute 分
* @param second 秒
* @param millis ミリ秒
* @return 日付
*/
public static Date makeFrom(int year, int month, int day, int hourOfDay, int minute, int second, int millis) {
Calendar calendar = Calendar.getInstance();
calendar.setLenient(true);
calendar.set(year, month - 1 /* zero origin */, day, hourOfDay, minute, second);
calendar.set(Calendar.MILLISECOND, millis);
return calendar.getTime();
}
/**
* An easy and non-deprecated non-lenient way of creating Date objects.
*
* @param year
* the year, e.g. 2007 is year 2007
* @param month
* the month, where 1 == January
* @param dayOfMonth
* the day of the month, where 1 == first day of the month
* @param hour
* the hour in 24 hour format where 0 == midnight
* @param minute
* is the minute 0-59
* @param second
* is the seconds 0-59
* @return a Date object with time set to midnight, ie. hour = 00, minutes = 00, seconds = 00 and milliseconds = 000
*/
public static Date date(final int year, final int month, final int dayOfMonth, final int hour, final int minute,
final int second) {
final Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.set(year, month - 1, dayOfMonth, hour, minute, second);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}