Java Code Examples for java.util.Calendar#SECOND

The following examples show how to use java.util.Calendar#SECOND . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DateUtilsRoundingTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests DateUtils.round()-method with Calendar.SECOND
 * Includes rounding the extremes of one second 
 * Includes rounding to January 1
 * 
 * @throws Exception
 * @since 3.0
 */
@Test
public void testRoundSecond() throws Exception {
    final int calendarField = Calendar.SECOND;
    Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
    Date minDate, maxDate;

    roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:15.000");
    roundedDownDate = targetSecondDate;
    lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:14.499");
    baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate,  calendarField);
    
    //round to January 1
    minDate = dateTimeParser.parse("December 31, 2007 23:59:59.500");
    maxDate = dateTimeParser.parse("January 1, 2008 0:00:00.499");
    roundToJanuaryFirst(minDate, maxDate, calendarField);
}
 
Example 2
Source File: DateUtilsRoundingTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Tests DateUtils.round()-method with Calendar.SECOND
 * Includes rounding the extremes of one second 
 * Includes rounding to January 1
 * 
 * @throws Exception
 * @since 3.0
 */
public void testRoundSecond() throws Exception {
    final int calendarField = Calendar.SECOND;
    Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
    Date minDate, maxDate;

    roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:15.000");
    roundedDownDate = targetSecondDate;
    lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:14.499");
    baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate,  calendarField);
    
    //round to January 1
    minDate = dateTimeParser.parse("December 31, 2007 23:59:59.500");
    maxDate = dateTimeParser.parse("January 1, 2008 0:00:00.499");
    roundToJanuaryFirst(minDate, maxDate, calendarField);
}
 
Example 3
Source File: DateUtil.java    From AsuraFramework with Apache License 2.0 6 votes vote down vote up
private static int translate(final IntervalUnit unit) {
	switch (unit) {
	case DAY:
		return Calendar.DAY_OF_YEAR;
	case HOUR:
		return Calendar.HOUR_OF_DAY;
	case MINUTE:
		return Calendar.MINUTE;
	case MONTH:
		return Calendar.MONTH;
	case SECOND:
		return Calendar.SECOND;
	case MILLISECOND:
		return Calendar.MILLISECOND;
	case WEEK:
		return Calendar.WEEK_OF_YEAR;
	case YEAR:
		return Calendar.YEAR;
	default:
		throw new IllegalArgumentException("Unknown IntervalUnit");
	}
}
 
Example 4
Source File: DateUtil.java    From phone with Apache License 2.0 6 votes vote down vote up
/**
 * 获取第一时间点 当前年,不可变更
 * 
 * @param field
 *            Calendar.field
 * @return
 */
public static Calendar getLastDate(int field, Date date) {
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(date);
	switch (field) {
	case Calendar.YEAR:
		calendar.set(Calendar.MONTH, 11);
	case Calendar.MONTH:
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DATE));
	case Calendar.DAY_OF_MONTH:
		calendar.set(Calendar.HOUR_OF_DAY, 23);
	case Calendar.HOUR_OF_DAY:
		calendar.set(Calendar.MINUTE, 59);
	case Calendar.MINUTE:
		calendar.set(Calendar.SECOND, 59);
	case Calendar.SECOND:
		calendar.set(Calendar.MILLISECOND, 999);
	default:
		break;
	}
	return calendar;
}
 
Example 5
Source File: BaseDateTimeType.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the given amount to the field specified by theField
 *
 * @param theField
 *           The field, uses constants from {@link Calendar} such as {@link Calendar#YEAR}
 * @param theValue
 *           The number to add (or subtract for a negative number)
 */
public void add(int theField, int theValue) {
	switch (theField) {
	case Calendar.YEAR:
		setValue(DateUtils.addYears(getValue(), theValue), getPrecision());
		break;
	case Calendar.MONTH:
		setValue(DateUtils.addMonths(getValue(), theValue), getPrecision());
		break;
	case Calendar.DATE:
		setValue(DateUtils.addDays(getValue(), theValue), getPrecision());
		break;
	case Calendar.HOUR:
		setValue(DateUtils.addHours(getValue(), theValue), getPrecision());
		break;
	case Calendar.MINUTE:
		setValue(DateUtils.addMinutes(getValue(), theValue), getPrecision());
		break;
	case Calendar.SECOND:
		setValue(DateUtils.addSeconds(getValue(), theValue), getPrecision());
		break;
	case Calendar.MILLISECOND:
		setValue(DateUtils.addMilliseconds(getValue(), theValue), getPrecision());
		break;
	default:
		throw new DataFormatException("Unknown field constant: " + theField);
	}
}
 
Example 6
Source File: SimCalendar.java    From jaamsim with Apache License 2.0 5 votes vote down vote up
/**
 * Sets this Calendar's current time from the given long value.
 * @param millis - time in milliseconds from the epoch
 */
@Override
public void setTimeInMillis(long millis) {

	// Gregorian calendar
	if (gregorian) {
		super.setTimeInMillis(millis);
		return;
	}

	// Simple calendar with 365 days per year
	long seconds = millis / millisPerSec;
	long minutes = millis / millisPerMin;
	long hours = millis / millisPerHr;
	long days = millis / millisPerDay;
	long years = millis / millisPerYr;

	int dayOfYear = (int) (days % 365L) + 1;  // dayOfYear = 1 - 365;
	int month = getMonthForDay(dayOfYear);    // month = 0 - 11
	int dayOfMonth = dayOfYear - firstDayOfMonth[month] + 1;

	super.set(Calendar.YEAR, (int) years + epoch);
	super.set(Calendar.MONTH, month);
	super.set(Calendar.DAY_OF_MONTH, dayOfMonth);
	super.set(Calendar.HOUR_OF_DAY, (int) (hours % 24L));
	super.set(Calendar.MINUTE, (int) (minutes % 60L));
	super.set(Calendar.SECOND, (int) (seconds % 60L));
	super.set(Calendar.MILLISECOND, (int) (millis % 1000L));
}
 
Example 7
Source File: AbstractCalendarValidator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Compares a calendar time value to another, indicating whether it is
 *    equal, less then or more than at a specified level.</p>
 *
 * @param value The Calendar value.
 * @param compare The <code>Calendar</code> to check the value against.
 * @param field The field <i>level</i> to compare to - e.g. specifying
 *        <code>Calendar.MINUTE</code> will compare the hours and minutes
 *        portions of the calendar.
 * @return Zero if the first value is equal to the second, -1
 *         if it is less than the second or +1 if it is greater than the second.
 */
protected int compareTime(Calendar value, Calendar compare, int field) {

    int result = 0;

    // Compare Hour
    result = calculateCompareResult(value, compare, Calendar.HOUR_OF_DAY);
    if (result != 0 || (field == Calendar.HOUR || field == Calendar.HOUR_OF_DAY)) {
        return result;
    }

    // Compare Minute
    result = calculateCompareResult(value, compare, Calendar.MINUTE);
    if (result != 0 || field == Calendar.MINUTE) {
        return result;
    }

    // Compare Second
    result = calculateCompareResult(value, compare, Calendar.SECOND);
    if (result != 0 || field == Calendar.SECOND) {
        return result;
    }

    // Compare Milliseconds
    if (field == Calendar.MILLISECOND) {
        return calculateCompareResult(value, compare, Calendar.MILLISECOND);
    }

    throw new IllegalArgumentException("Invalid field: " + field);

}
 
Example 8
Source File: SybaseDatabaseType.java    From reladomo with Apache License 2.0 5 votes vote down vote up
public void set(int field, int value)
{
    switch(field)
    {
        case Calendar.YEAR:
            this.year = value;
            break;
        case Calendar.MONTH:
            this.month = value;
            break;
        case Calendar.DAY_OF_MONTH:
            this.dayOfMonth = value;
            break;
        case Calendar.HOUR_OF_DAY:
            this.hourOfDay = value;
            break;
        case Calendar.MINUTE:
            this.minute = value;
            break;
        case Calendar.SECOND:
            this.second = value;
            break;
        case Calendar.MILLISECOND:
            this.millis = value;
            break;
        default:
            throw new RuntimeException("unexpected set method for field "+field);
    }
}
 
Example 9
Source File: DateAdjust.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
public Adjustment(int field, int amount) {
	this.originalField = field;

	switch (field) {
		case CALENDAR_FIELD_YEAR:
			this.calendarField = Calendar.YEAR;
			break;
		case CALENDAR_FIELD_MONTH:
			this.calendarField = Calendar.MONTH;
			break;
		case CALENDAR_FIELD_DAY:
			this.calendarField = Calendar.DAY_OF_YEAR;
			break;
		case CALENDAR_FIELD_HOUR:
			this.calendarField = Calendar.HOUR_OF_DAY;
			break;
		case CALENDAR_FIELD_MINUTE:
			this.calendarField = Calendar.MINUTE;
			break;
		case CALENDAR_FIELD_SECOND:
			this.calendarField = Calendar.SECOND;
			break;
		case CALENDAR_FIELD_MILLISECOND:
			this.calendarField = Calendar.MILLISECOND;
			break;
	}

	this.amount = amount;
}
 
Example 10
Source File: DateDifference.java    From ApprovalTests.Java with Apache License 2.0 5 votes vote down vote up
public static int convertUnitString(String unit)
{
  int result = 0;
  if (MILLISECONDS.equalsIgnoreCase(unit))
  {
    result = Calendar.MILLISECOND;
  }
  else if (SECONDS.equalsIgnoreCase(unit))
  {
    result = Calendar.SECOND;
  }
  else if (MINUTES.equalsIgnoreCase(unit))
  {
    result = Calendar.MINUTE;
  }
  else if (HOURS.equalsIgnoreCase(unit))
  {
    result = Calendar.HOUR;
  }
  else if (DAYS.equalsIgnoreCase(unit))
  {
    result = Calendar.DATE;
  }
  else if (WEEKS.equalsIgnoreCase(unit))
  {
    result = Calendar.WEEK_OF_YEAR;
  }
  else if (MONTHS.equalsIgnoreCase(unit))
  {
    result = Calendar.MONTH;
  }
  else if (YEARS.equalsIgnoreCase(unit))
  {
    result = Calendar.YEAR;
  }
  return result;
}
 
Example 11
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private MainPanel() {
  super(new GridLayout(2, 1));

  Calendar c = Calendar.getInstance();
  // c.clear(Calendar.HOUR_OF_DAY);
  // c.clear(Calendar.AM_PM);
  // c.clear(Calendar.HOUR);
  c.set(Calendar.HOUR_OF_DAY, 0);
  c.clear(Calendar.MINUTE);
  c.clear(Calendar.SECOND);
  c.clear(Calendar.MILLISECOND);
  Date d = c.getTime();

  SimpleDateFormat format = new SimpleDateFormat("mm:ss", Locale.getDefault());
  DefaultFormatterFactory factory = new DefaultFormatterFactory(new DateFormatter(format));

  JSpinner spinner1 = new JSpinner(new SpinnerDateModel(d, null, null, Calendar.SECOND));
  ((JSpinner.DefaultEditor) spinner1.getEditor()).getTextField().setFormatterFactory(factory);

  JSpinner spinner2 = new JSpinner(new SpinnerDateModel(d, null, null, Calendar.SECOND) {
    @Override public void setCalendarField(int calendarField) {
      // https://docs.oracle.com/javase/8/docs/api/javax/swing/SpinnerDateModel.html#setCalendarField-int-
      // If you only want one field to spin you can subclass and ignore the setCalendarField calls.
    }
  });
  ((JSpinner.DefaultEditor) spinner2.getEditor()).getTextField().setFormatterFactory(factory);

  add(makeTitledPanel("Default SpinnerDateModel", spinner1));
  add(makeTitledPanel("Override SpinnerDateModel#setCalendarField(...)", spinner2));
  setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
  setPreferredSize(new Dimension(320, 240));
}
 
Example 12
Source File: DateUtils.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Gets a Calendar fragment for any unit.
 * 
 * @param calendar the calendar to work with, not null
 * @param fragment the Calendar field part of calendar to calculate 
 * @param unit the {@code Calendar} field defining the unit
 * @return number of units within the fragment of the calendar
 * @throws IllegalArgumentException if the date is <code>null</code> or 
 * fragment is not supported
 * @since 2.4
 */
private static long getFragment(final Calendar calendar, final int fragment, final int unit) {
    if(calendar == null) {
        throw  new IllegalArgumentException("The date must not be null"); 
    }
    final long millisPerUnit = getMillisPerUnit(unit);
    long result = 0;
    
    // Fragments bigger than a day require a breakdown to days
    switch (fragment) {
        case Calendar.YEAR:
            result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
            break;
        case Calendar.MONTH:
            result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
            break;
    }

    switch (fragment) {
        // Number of days already calculated for these cases
        case Calendar.YEAR:
        case Calendar.MONTH:
        
        // The rest of the valid cases
        case Calendar.DAY_OF_YEAR:
        case Calendar.DATE:
            result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.HOUR_OF_DAY:
            result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.MINUTE:
            result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.SECOND:
            result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
            break;
        case Calendar.MILLISECOND: break;//never useful
            default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
    }
    return result;
}
 
Example 13
Source File: TimeRangeShardLocator.java    From das with Apache License 2.0 4 votes vote down vote up
TimeRangeShardLocator(TimeRangeStrategy.TIME_PATTERN timePattern) {
    switch (timePattern){
        case WEEK_OF_YEAR:
            field = Calendar.WEEK_OF_YEAR;
            range = Range.atLeast(1);
            period = DAY * 366L;
            break;
        case WEEK_OF_MONTH:
            field = Calendar.WEEK_OF_MONTH;
            range = Range.atLeast(1);
            period = DAY * 31L;
            break;
        case DAY_OF_MONTH:
            field = Calendar.DAY_OF_MONTH;
            range = Range.atLeast(1);
            period = DAY * 31L;
            break;
        case DAY_OF_YEAR:
            field = Calendar.DAY_OF_YEAR;
            range = Range.atLeast(1);
            period = DAY * 366L;
            break;
        case DAY_OF_WEEK:
            field = Calendar.DAY_OF_WEEK;
            range = Range.closed(1, 7);
            period = DAY * 7;
            break;
        case HOUR_OF_DAY:
            field = Calendar.HOUR_OF_DAY;
            range = Range.closed(0, 23);
            period = DAY;
            break;
        case MINUTE_OF_HOUR:
            field = Calendar.MINUTE;
            range = Range.closed(0, 59);
            period = HOUR;
            break;
        case SECOND_OF_MINUTE:
            field = Calendar.SECOND;
            range = Range.closed(0, 59);
            period = MINUTE;
            break;
    }
}
 
Example 14
Source File: DateTimeType.java    From evosql with Apache License 2.0 4 votes vote down vote up
public int getPart(Session session, Object dateTime, int part) {

        int calendarPart;
        int increment = 0;
        int divisor   = 1;

        switch (part) {

            case Types.SQL_INTERVAL_YEAR :
                calendarPart = Calendar.YEAR;
                break;

            case Types.SQL_INTERVAL_MONTH :
                increment    = 1;
                calendarPart = Calendar.MONTH;
                break;

            case Types.SQL_INTERVAL_DAY :
            case DAY_OF_MONTH :
                calendarPart = Calendar.DAY_OF_MONTH;
                break;

            case Types.SQL_INTERVAL_HOUR :
                calendarPart = Calendar.HOUR_OF_DAY;
                break;

            case Types.SQL_INTERVAL_MINUTE :
                calendarPart = Calendar.MINUTE;
                break;

            case Types.SQL_INTERVAL_SECOND :
                calendarPart = Calendar.SECOND;
                break;

            case DAY_OF_WEEK :
                calendarPart = Calendar.DAY_OF_WEEK;
                break;

            case WEEK_OF_YEAR :
                calendarPart = Calendar.WEEK_OF_YEAR;
                break;

            case SECONDS_MIDNIGHT : {
                if (typeCode == Types.SQL_TIME
                        || typeCode == Types.SQL_TIME_WITH_TIME_ZONE) {}
                else {
                    try {
                        Type target = withTimeZone
                                      ? Type.SQL_TIME_WITH_TIME_ZONE
                                      : Type.SQL_TIME;

                        dateTime = target.castToType(session, dateTime, this);
                    } catch (HsqlException e) {}
                }

                return ((TimeData) dateTime).getSeconds();
            }
            case TIMEZONE_HOUR :
                if (typeCode == Types.SQL_TIMESTAMP_WITH_TIME_ZONE) {
                    return ((TimestampData) dateTime).getZone() / 3600;
                } else {
                    return ((TimeData) dateTime).getZone() / 3600;
                }
            case TIMEZONE_MINUTE :
                if (typeCode == Types.SQL_TIMESTAMP_WITH_TIME_ZONE) {
                    return ((TimestampData) dateTime).getZone() / 60 % 60;
                } else {
                    return ((TimeData) dateTime).getZone() / 60 % 60;
                }
            case QUARTER :
                increment    = 1;
                divisor      = 3;
                calendarPart = Calendar.MONTH;
                break;

            case DAY_OF_YEAR :
                calendarPart = Calendar.DAY_OF_YEAR;
                break;

            default :
                throw Error.runtimeError(ErrorCode.U_S0500,
                                         "DateTimeType - " + part);
        }

        long millis = getMillis(dateTime);

        return HsqlDateTime.getDateTimePart(millis, calendarPart) / divisor
               + increment;
    }
 
Example 15
Source File: Lang_21_DateUtils_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Calendar-version for fragment-calculation in any unit
 * 
 * @param calendar the calendar to work with, not null
 * @param fragment the Calendar field part of calendar to calculate 
 * @param unit Calendar field defining the unit
 * @return number of units within the fragment of the calendar
 * @throws IllegalArgumentException if the date is <code>null</code> or 
 * fragment is not supported
 * @since 2.4
 */
private static long getFragment(Calendar calendar, int fragment, int unit) {
    if(calendar == null) {
        throw  new IllegalArgumentException("The date must not be null"); 
    }
    long millisPerUnit = getMillisPerUnit(unit);
    long result = 0;
    
    // Fragments bigger than a day require a breakdown to days
    switch (fragment) {
        case Calendar.YEAR:
            result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
            break;
        case Calendar.MONTH:
            result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
            break;
    }

    switch (fragment) {
        // Number of days already calculated for these cases
        case Calendar.YEAR:
        case Calendar.MONTH:
        
        // The rest of the valid cases
        case Calendar.DAY_OF_YEAR:
        case Calendar.DATE:
            result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.HOUR_OF_DAY:
            result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.MINUTE:
            result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.SECOND:
            result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
            break;
        case Calendar.MILLISECOND: break;//never useful
            default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
    }
    return result;
}
 
Example 16
Source File: RoundScaleTickLabels.java    From nebula with Eclipse Public License 2.0 4 votes vote down vote up
/**
     * Gets the grid step.
     * 
     * @param lengthInPixels
     *            scale length in pixels
     * @param min
     *            minimum value
     * @param max
     *            maximum value
     * @return rounded value.
     */
    private double getGridStep(int lengthInPixels, final double minR, final double maxR) {
    	if((int) scale.getMajorGridStep() != 0) {
    		return scale.getMajorGridStep();
    	}
    	double min = minR, max = maxR;
        if (lengthInPixels <= 0) {
            lengthInPixels = 1;
        }
        boolean minBigger = false;
        if (min >= max) {        	
        	if(max == min)
        		max ++;
        	else{
        		minBigger = true;
        		double swap = min;
        		min = max;
        		max= swap;
        	}
//        		throw new IllegalArgumentException("min must be less than max.");
        }

        double length = Math.abs(max - min);
        double markStepHint = scale.getMajorTickMarkStepHint();
        if(markStepHint > lengthInPixels)
        	markStepHint = lengthInPixels;
        double gridStepHint = length / lengthInPixels
                * markStepHint;       	
        
        if(scale.isDateEnabled()) {
        	//by default, make the least step to be minutes
        	long timeStep = 60000l;       		
        	if (scale.getTimeUnit() == Calendar.SECOND) {
        		timeStep = 1000l;
        	} else if (scale.getTimeUnit() == Calendar.MINUTE) {
        		timeStep = 60000l;
        	}else if (scale.getTimeUnit() == Calendar.HOUR_OF_DAY) {
        		timeStep = 3600000l;
        	}else if (scale.getTimeUnit() == Calendar.DATE) {
        		timeStep = 86400000l;
        	}else if (scale.getTimeUnit() == Calendar.MONTH) {
        		timeStep = 30l*86400000l;
        	}else if (scale.getTimeUnit() == Calendar.YEAR) {
        		timeStep = 365l*86400000l;  
        	}
        	double temp = gridStepHint + (timeStep - gridStepHint%timeStep);       	
        	return temp;
        }
        
        double mantissa = gridStepHint;
        int exp = 0;
        if (mantissa < 1) {
        	if(mantissa != 0){
	            while (mantissa < 1) {
	                mantissa *= 10.0;
	                exp--;
	            }
            }
        } else {
            while (mantissa >= 10) {
                mantissa /= 10.0;
                exp++;
            }
        }

        double gridStep;
		if (mantissa > 7.5) {
			// 10*10^exp
			gridStep = 10 * Math.pow(10, exp);
		} else if (mantissa > 3.5) {
			// 5*10^exp
			gridStep = 5 * Math.pow(10, exp);
		} else if (mantissa > 1.5) {
			// 2.0*10^exp
			gridStep = 2 * Math.pow(10, exp);
		} else {
			gridStep = Math.pow(10, exp); // 1*10^exponent
		}
		if (minBigger)
			gridStep = -gridStep;
		return gridStep;
    }
 
Example 17
Source File: PathResolver.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@ElFunction(name = "ss")
public static int ss() {
  adjustTimeUnit(Calendar.SECOND);
  return Calendar.SECOND;
}
 
Example 18
Source File: DateTimeUtil.java    From sophia_scaffolding with Apache License 2.0 4 votes vote down vote up
/**
 * 把给定的时间加上指定的时间值,可以为负
 *
 * @param d
 *            需要设定的日期对象
 * @param times
 *            时间值
 * @param type
 *            类型,Calendar.MILLISECOND,毫秒<BR>
 *            Calendar.SECOND,秒<BR>
 *            Calendar.MINUTE,分钟<BR>
 *            Calendar.HOUR,小时<BR>
 *            Calendar.DATE,日<BR>
 * @return 如果d为null,返回null
 */
public static Date addTime(Date d, double times, int type) {
    if (d == null) {
        throw new IllegalArgumentException("参数d不能是null对象!");
    }
    long qv = 1;
    switch (type) {
        case Calendar.MILLISECOND:
            qv = 1;
            break;
        case Calendar.SECOND:
            qv = 1000;
            break;
        case Calendar.MINUTE:
            qv = 1000 * 60;
            break;
        case Calendar.HOUR:
            qv = 1000 * 60 * 60;
            break;
        case Calendar.DATE:
            qv = 1000 * 60 * 60 * 24;
            break;
        default:
            throw new RuntimeException("时间类型不正确!type=" + type);
    }
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(d);
    long milliseconds = (long) Math.round(Math.abs(times) * qv);
    if (times > 0) {
        for (; milliseconds > 0; milliseconds -= 2147483647) {
            if (milliseconds > 2147483647) {
                calendar.add(Calendar.MILLISECOND, 2147483647);
            } else {
                calendar.add(Calendar.MILLISECOND, (int) milliseconds);
            }
        }
    } else {
        for (; milliseconds > 0; milliseconds -= 2147483647) {
            if (milliseconds > 2147483647) {
                calendar.add(Calendar.MILLISECOND, -2147483647);
            } else {
                calendar.add(Calendar.MILLISECOND, -(int) milliseconds);
            }
        }
    }
    return calendar.getTime();
}
 
Example 19
Source File: DateUtils.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Calendar-version for fragment-calculation in any unit
 * 
 * @param calendar the calendar to work with, not null
 * @param fragment the Calendar field part of calendar to calculate 
 * @param unit Calendar field defining the unit
 * @return number of units within the fragment of the calendar
 * @throws IllegalArgumentException if the date is <code>null</code> or 
 * fragment is not supported
 * @since 2.4
 */
private static long getFragment(Calendar calendar, int fragment, int unit) {
    if(calendar == null) {
        throw  new IllegalArgumentException("The date must not be null"); 
    }
    long millisPerUnit = getMillisPerUnit(unit);
    long result = 0;
    
    // Fragments bigger than a day require a breakdown to days
    switch (fragment) {
        case Calendar.YEAR:
            result += (calendar.get(Calendar.DAY_OF_YEAR) * MILLIS_PER_DAY) / millisPerUnit;
            break;
        case Calendar.MONTH:
            result += (calendar.get(Calendar.DAY_OF_MONTH) * MILLIS_PER_DAY) / millisPerUnit;
            break;
    }

    switch (fragment) {
        // Number of days already calculated for these cases
        case Calendar.YEAR:
        case Calendar.MONTH:
        
        // The rest of the valid cases
        case Calendar.DAY_OF_YEAR:
        case Calendar.DATE:
            result += (calendar.get(Calendar.HOUR_OF_DAY) * MILLIS_PER_HOUR) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.HOUR_OF_DAY:
            result += (calendar.get(Calendar.MINUTE) * MILLIS_PER_MINUTE) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.MINUTE:
            result += (calendar.get(Calendar.SECOND) * MILLIS_PER_SECOND) / millisPerUnit;
            //$FALL-THROUGH$
        case Calendar.SECOND:
            result += (calendar.get(Calendar.MILLISECOND) * 1) / millisPerUnit;
            break;
        case Calendar.MILLISECOND: break;//never useful
            default: throw new IllegalArgumentException("The fragment " + fragment + " is not supported");
    }
    return result;
}
 
Example 20
Source File: DateUtilsRoundingTest.java    From astor with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Test DateUtils.truncate()-method with Calendar.SECOND
 * 
 * @throws Exception
 * @since 3.0
 */
public void testTruncateSecond() throws Exception {
    final int calendarField = Calendar.SECOND;
    Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 8:15:14.999");
    baseTruncateTest(targetSecondDate, lastTruncateDate, calendarField);
}