Java Code Examples for java.util.Calendar#MILLISECOND

The following examples show how to use java.util.Calendar#MILLISECOND . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
/** Maps the name of the unit to an integer unit identifier of {@link Calendar} */
private int mapUnitNameToIndex(String unit) {
	switch (unit) {
		case ExpressionParserConstants.DATE_UNIT_YEAR:
			return Calendar.YEAR;
		case ExpressionParserConstants.DATE_UNIT_MONTH:
			return Calendar.MONTH;
		case ExpressionParserConstants.DATE_UNIT_WEEK:
			return Calendar.WEEK_OF_YEAR;
		case ExpressionParserConstants.DATE_UNIT_DAY:
			return Calendar.DAY_OF_MONTH;

		case ExpressionParserConstants.DATE_UNIT_HOUR:
			return Calendar.HOUR_OF_DAY;
		case ExpressionParserConstants.DATE_UNIT_MINUTE:
			return Calendar.MINUTE;
		case ExpressionParserConstants.DATE_UNIT_SECOND:
			return Calendar.SECOND;
		case ExpressionParserConstants.DATE_UNIT_MILLISECOND:
			return Calendar.MILLISECOND;
		default:
			throw new FunctionInputException("expression_parser.function_wrong_type_at", getFunctionName(),
					"unit constant", "third");
	}
}
 
Example 2
Source Project: astor   File: DateUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the number of millis of a datefield, if this is a constant value
 * 
 * @param unit A Calendar field which is a valid unit for a fragment
 * @return number of millis
 * @throws IllegalArgumentException if date can't be represented in millisenconds
 * @since 2.4 
 */
private static long getMillisPerUnit(int unit) {
    long result = Long.MAX_VALUE;
    switch (unit) {
        case Calendar.DAY_OF_YEAR:
        case Calendar.DATE:
            result = MILLIS_PER_DAY;
            break;
        case Calendar.HOUR_OF_DAY:
            result = MILLIS_PER_HOUR;
            break;
        case Calendar.MINUTE:
            result = MILLIS_PER_MINUTE;
            break;
        case Calendar.SECOND:
            result = MILLIS_PER_SECOND;
            break;
        case Calendar.MILLISECOND:
            result = 1;
            break;
        default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
    }
    return result;
}
 
Example 3
Source Project: astor   File: DateUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the number of milliseconds of a {@code Calendar} field, if this is a constant value.
 * This handles millisecond, second, minute, hour and day (even though days can very in length).
 * 
 * @param unit  a {@code Calendar} field constant which is a valid unit for a fragment
 * @return the number of milliseconds in the field
 * @throws IllegalArgumentException if date can't be represented in milliseconds
 * @since 2.4 
 */
private static long getMillisPerUnit(int unit) {
    long result = Long.MAX_VALUE;
    switch (unit) {
        case Calendar.DAY_OF_YEAR:
        case Calendar.DATE:
            result = MILLIS_PER_DAY;
            break;
        case Calendar.HOUR_OF_DAY:
            result = MILLIS_PER_HOUR;
            break;
        case Calendar.MINUTE:
            result = MILLIS_PER_MINUTE;
            break;
        case Calendar.SECOND:
            result = MILLIS_PER_SECOND;
            break;
        case Calendar.MILLISECOND:
            result = 1;
            break;
        default: throw new IllegalArgumentException("The unit " + unit + " cannot be represented is milleseconds");
    }
    return result;
}
 
Example 4
Source Project: jaamsim   File: SimCalendar.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the time in milliseconds from the epoch corresponding to the specified date.
 * @param year - year
 * @param month - month (0 - 11)
 * @param dayOfMonth - day of the month (1 - 31)
 * @param hourOfDay - hour of the day (0 - 23)
 * @param minute - minutes (0 - 59)
 * @param second - seconds (0 - 59)
 * @param millis - millisecond (0 - 999)
 * @return time in milliseconds from the epoch
 */
public long getTimeInMillis(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second, int millis) {

	// Gregorian calendar
	if (gregorian) {
		super.set(year, month, dayOfMonth, hourOfDay, minute, second);
		super.set(Calendar.MILLISECOND, millis);
		return super.getTimeInMillis();
	}

	// Simple calendar with 365 days per year
	long ret = 0;
	ret += (year - epoch) * millisPerYr;
	ret += (firstDayOfMonth[month] - 1) * millisPerDay;
	ret += (dayOfMonth - 1) * millisPerDay;
	ret += hourOfDay * millisPerHr;
	ret += minute * millisPerMin;
	ret += second * millisPerSec;
	ret += millis;
	return ret;
}
 
Example 5
/**
 * 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
/**
 * Tests DateUtils.round()-method with Calendar.MILLISECOND
 * Includes rounding the extremes of one second 
 * Includes rounding to January 1
 * 
 * @throws Exception
 * @since 3.0
 */
@Test
public void testRoundMilliSecond() throws Exception {
    final int calendarField = Calendar.MILLISECOND;
    Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
    Date minDate, maxDate;

    roundedDownDate = lastRoundedDownDate = targetMilliSecondDate;
    roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:14.232");
    baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate,  calendarField);
    
    //round to January 1
    minDate = maxDate = januaryOneDate;
    roundToJanuaryFirst(minDate, maxDate, calendarField);
}
 
Example 7
Source Project: cql_engine   File: FhirModelResolver.java    License: Apache License 2.0 5 votes vote down vote up
protected DateTime toDateTime(BaseDateTimeType value, Integer calendarConstant) {
    Calendar calendar = this.getCalendar(value);

    TimeZone tz = calendar.getTimeZone() == null ? TimeZone.getDefault() : calendar.getTimeZone();
    ZoneOffset zoneOffset = tz.toZoneId().getRules().getStandardOffset(calendar.toInstant());
    switch (calendarConstant) {
        case Calendar.YEAR: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                calendar.get(Calendar.YEAR)
        );
        case Calendar.MONTH: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1
        );
        case Calendar.DAY_OF_MONTH: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)
        );
        case Calendar.HOUR_OF_DAY: return new DateTime(
            TemporalHelper.zoneToOffset(zoneOffset),
            calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY)
        );
        case Calendar.MINUTE: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE)
        );
        case Calendar.SECOND: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND)
        );
        case Calendar.MILLISECOND: return new DateTime(
                TemporalHelper.zoneToOffset(zoneOffset),
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND), calendar.get(Calendar.MILLISECOND)
        );
        default: throw new InvalidPrecision(String.format("Invalid temporal precision %s", calendarConstant));
    }
}
 
Example 8
Source Project: reladomo   File: SybaseDatabaseType.java    License: 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 Project: mumu   File: DateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据单位字段比较两个时间
 * 
 * @param date
 *            时间1
 * @param otherDate
 *            时间2
 * @param withUnit
 *            单位字段,从Calendar field取值
 * @return 等于返回0值, 大于返回大于0的值 小于返回小于0的值
 */
public static int compareTime(Date date, Date otherDate, int withUnit) {
	Calendar dateCal = Calendar.getInstance();
	dateCal.setTime(date);
	Calendar otherDateCal = Calendar.getInstance();
	otherDateCal.setTime(otherDate);

	dateCal.clear(Calendar.YEAR);
	dateCal.clear(Calendar.MONTH);
	dateCal.set(Calendar.DATE, 1);
	otherDateCal.clear(Calendar.YEAR);
	otherDateCal.clear(Calendar.MONTH);
	otherDateCal.set(Calendar.DATE, 1);
	switch (withUnit) {
	case Calendar.HOUR:
		dateCal.clear(Calendar.MINUTE);
		otherDateCal.clear(Calendar.MINUTE);
	case Calendar.MINUTE:
		dateCal.clear(Calendar.SECOND);
		otherDateCal.clear(Calendar.SECOND);
	case Calendar.SECOND:
		dateCal.clear(Calendar.MILLISECOND);
		otherDateCal.clear(Calendar.MILLISECOND);
	case Calendar.MILLISECOND:
		break;
	default:
		throw new IllegalArgumentException("withUnit 单位字段 " + withUnit + " 不合法!!");
	}
	return dateCal.compareTo(otherDateCal);
}
 
Example 10
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
/**
 * Tests DateUtils.round()-method with Calendar.MILLISECOND
 * Includes rounding the extremes of one second 
 * Includes rounding to January 1
 * 
 * @throws Exception
 * @since 3.0
 */
public void testRoundMilliSecond() throws Exception {
    final int calendarField = Calendar.MILLISECOND;
    Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
    Date minDate, maxDate;

    roundedDownDate = lastRoundedDownDate = targetMilliSecondDate;
    roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:14.232");
    baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate,  calendarField);
    
    //round to January 1
    minDate = maxDate = januaryOneDate;
    roundToJanuaryFirst(minDate, maxDate, calendarField);
}
 
Example 12
Source Project: roncoo-pay   File: DateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据单位字段比较两个日期
 * 
 * @param date
 *            日期1
 * @param otherDate
 *            日期2
 * @param withUnit
 *            单位字段,从Calendar field取值
 * @return 等于返回0值, 大于返回大于0的值 小于返回小于0的值
 */
public static int compareDate(Date date, Date otherDate, int withUnit) {
	Calendar dateCal = Calendar.getInstance();
	dateCal.setTime(date);
	Calendar otherDateCal = Calendar.getInstance();
	otherDateCal.setTime(otherDate);

	switch (withUnit) {
	case Calendar.YEAR:
		dateCal.clear(Calendar.MONTH);
		otherDateCal.clear(Calendar.MONTH);
	case Calendar.MONTH:
		dateCal.set(Calendar.DATE, 1);
		otherDateCal.set(Calendar.DATE, 1);
	case Calendar.DATE:
		dateCal.set(Calendar.HOUR_OF_DAY, 0);
		otherDateCal.set(Calendar.HOUR_OF_DAY, 0);
	case Calendar.HOUR:
		dateCal.clear(Calendar.MINUTE);
		otherDateCal.clear(Calendar.MINUTE);
	case Calendar.MINUTE:
		dateCal.clear(Calendar.SECOND);
		otherDateCal.clear(Calendar.SECOND);
	case Calendar.SECOND:
		dateCal.clear(Calendar.MILLISECOND);
		otherDateCal.clear(Calendar.MILLISECOND);
	case Calendar.MILLISECOND:
		break;
	default:
		throw new IllegalArgumentException("withUnit 单位字段 " + withUnit + " 不合法!!");
	}
	return dateCal.compareTo(otherDateCal);
}
 
Example 13
Source Project: lams   File: DateBuilder.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static int translate(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 14
/**
     * Get length of bill period.
     *
     * @param period period type
     * @return array of [Calendar.FIELD, amount]
     */
    private static int[] getPeriodSettings(final int period) {
        int f; // Calendar.FIELD
        int v; // amount
        /*
         * The values j and k are used to add a different type of period to
* the value, eg. you can have a period of one month and for each
* month you can add one day so you would have the same day-number
* as start and end of the period. (01.01.2012 - 01.02.2012,
* 02.02.2012 - 02.03.2012 and so on...)
*/
        int j = Calendar.MILLISECOND; // Additional Calendar.FIELD
        int k = 0; // Additional amount
        switch (period) {
            case BILLPERIOD_DAY:
                f = Calendar.DAY_OF_MONTH;
                v = 1;
                break;
            case BILLPERIOD_28D:
                f = Calendar.DAY_OF_MONTH;
                v = 28;
                break;
            case BILLPERIOD_30D:
                f = Calendar.DAY_OF_MONTH;
                v = 30;
                break;
            case BILLPERIOD_31D:
                f = Calendar.DAY_OF_MONTH;
                v = 31;
                break;
            case BILLPERIOD_60D:
                f = Calendar.DAY_OF_MONTH;
                v = 60;
                break;
            case BILLPERIOD_90D:
                f = Calendar.DAY_OF_MONTH;
                v = 90;
                break;
            case BILLPERIOD_1MONTH:
                f = Calendar.MONTH;
                v = 1;
                break;
            case BILLPERIOD_2MONTH:
                f = Calendar.MONTH;
                v = 2;
                break;
            case BILLPERIOD_3MONTH:
                f = Calendar.MONTH;
                v = 3;
                break;
            case BILLPERIOD_4MONTH:
                f = Calendar.MONTH;
                v = 4;
                break;
            case BILLPERIOD_5MONTH:
                f = Calendar.MONTH;
                v = 5;
                break;
            case BILLPERIOD_6MONTH:
                f = Calendar.MONTH;
                v = 6;
                break;
            case BILLPERIOD_12MONTH:
                f = Calendar.YEAR;
                v = 1;
                break;
            case BILLPERIOD_1MONTH_1DAY:
                f = Calendar.MONTH;
                v = 1;
                j = Calendar.DAY_OF_MONTH;
                k = 1;
                break;
            case BILLPERIOD_WEEK:
                f = Calendar.DAY_OF_MONTH;
                v = 7;
                break;
            case BILLPERIOD_14D:
                f = Calendar.DAY_OF_MONTH;
                v = 14;
                break;
            case BILLPERIOD_15D:
                f = Calendar.DAY_OF_MONTH;
                v = 15;
                break;
            default:
                f = Calendar.MONTH;
                v = 1;
                break;
        }

        return new int[]{f, v, j, k};
    }
 
Example 15
Source Project: sophia_scaffolding   File: DateTimeUtil.java    License: 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 16
Source Project: nebula   File: DAxis.java    License: Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Formats the given object as a DateFormat if Date is enabled or as a
 * DecimalFormat. This is based on an internal format pattern given the
 * object in parameter. When formatting a date, if minOrMaxDate is true as
 * well as autoFormat, then the SimpleDateFormat us used to format the
 * object.
 *
 * @param obj
 *            the object
 * @param extraDP
 *            must be non-negative
 * @return the formatted string
 */
public String format(Object obj, int extraDP) {
	if (extraDP < 0) {
		throw new IllegalArgumentException("Number of extra decimal places must be non-negative");
	}
	String formatPattern = getFormatPattern();
	boolean autoFormat = isAutoFormat();
	if (cachedFormats.get(extraDP) == null) {
		if (isDateEnabled()) {
			if (autoFormat || formatPattern == null || formatPattern.equals("")
					|| formatPattern.equals(default_decimal_format)
					|| formatPattern.equals(DEFAULT_ENGINEERING_FORMAT)) {
				// (?) overridden anyway
				formatPattern = DEFAULT_DATE_FORMAT;
				int timeUnit = getTimeUnit();
				double length = Math.abs(max - min);
				// less than a second
				if (length <= 1000 || timeUnit == Calendar.MILLISECOND) {
					formatPattern = "HH:mm:ss.SSS";
				}
				// less than a hour
				else if (length <= 3600000d || timeUnit == Calendar.SECOND) {
					formatPattern = "HH:mm:ss";
				}
				// less than a day
				else if (length <= 86400000d || timeUnit == Calendar.MINUTE) {
					formatPattern = "HH:mm";
				}
				// less than a week
				else if (length <= 604800000d || timeUnit == Calendar.HOUR_OF_DAY) {
					formatPattern = "dd HH:mm";
				}
				// less than a month
				else if (length <= 2592000000d || timeUnit == Calendar.DATE) {
					formatPattern = "MMMMM d";
				}
				// less than a year
				else if (length <= 31536000000d || timeUnit == Calendar.MONTH) {
					formatPattern = "yyyy MMMMM";
				} else {// if (timeUnit == Calendar.YEAR) {
					formatPattern = "yyyy";
				}
				if (formatPattern == null || formatPattern.equals("")) {
					autoFormat = true;
				}
			}
			internalSetFormatPattern(formatPattern);
			cachedFormats.put(extraDP, new SimpleDateFormat(formatPattern));
		} else {
			if (formatPattern == null || formatPattern.isEmpty() || formatPattern.equals(default_decimal_format)
					|| formatPattern.equals(DEFAULT_DATE_FORMAT)) {
				formatPattern = getAutoFormat(min, max);
				internalSetFormatPattern(formatPattern);
				if (formatPattern == null || formatPattern.equals("")) {
					autoFormat = true;
				}
			}

			String ePattern = formatPattern;
			if (extraDP > 0) {
				int e = formatPattern.lastIndexOf('E');
				StringBuilder temp = new StringBuilder(e == -1 ? formatPattern : formatPattern.substring(0, e));
				for (int i = 0; i < extraDP; i++) {
					temp.append('#');
				}
				if (e != -1) {
					temp.append(formatPattern.substring(e));
				}
				ePattern = temp.toString();
			}
			cachedFormats.put(extraDP, new DecimalFormat(ePattern));
		}
		internalSetAutoFormat(autoFormat);
	}
	if (isDateEnabled() && obj instanceof Number) {
		return cachedFormats.get(extraDP).format(new Date(((Number) obj).longValue()));
	}
	return cachedFormats.get(extraDP).format(obj);
}
 
Example 17
Source Project: coming   File: Lang_21_DateUtils_s.java    License: 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 18
private GetTimeTextUseCase[] getTimeTextUseCases()
{
  return new GetTimeTextUseCase[]{new GetTimeTextUseCase(5, Calendar.YEAR, Calendar.MILLISECOND, "now", "",
      unitsArray, YEAR_MS, "1 Year, 0 Months, 0 Weeks, 0 Days, 0 Hours"),
                                  new GetTimeTextUseCase(5, Calendar.YEAR, Calendar.MILLISECOND, "now", "",
                                      unitsArray, YEAR_MS + (2 * MONTH_MS),
                                      "1 Year, 2 Months, 0 Weeks, 0 Days, 0 Hours"),
                                  new GetTimeTextUseCase(5, Calendar.YEAR, Calendar.MILLISECOND, "now", "",
                                      unitsArray, YEAR_MS - (2 * MONTH_MS),
                                      "10 Months, 0 Weeks, 5 Days, 0 Hours, 0 Mins"),
                                  new GetTimeTextUseCase(2, Calendar.YEAR, Calendar.MILLISECOND, "", "ago",
                                      unitsArray, YEAR_MS + (2 * MONTH_MS), "1 Year, 2 Months ago"),
                                  new GetTimeTextUseCase(5, Calendar.MILLISECOND, Calendar.MILLISECOND, "now",
                                      "", unitsArray, YEAR_MS + (2 * MONTH_MS), "36720000000 Millis"),
                                  new GetTimeTextUseCase(5, Calendar.YEAR, Calendar.DATE, "today", "ago",
                                      unitsArray, DAY_MS, "1 Day ago"),
                                  new GetTimeTextUseCase(5, Calendar.YEAR, Calendar.DATE, "today", "ago",
                                      unitsArray, DAY_MS - 1, "today"),
                                  new GetTimeTextUseCase(5, Calendar.YEAR, Calendar.MILLISECOND, "now", "",
                                      unitsArray, new GregorianCalendar(2003, 1, 28), /* 1 = Feb */
                                      new GregorianCalendar(2003, 2, 31),
                                      "1 Month, 0 Weeks, 1 Day, 0 Hours, 0 Mins"),
                                  new GetTimeTextUseCase(5, Calendar.YEAR, Calendar.MILLISECOND, "now", "",
                                      unitsArray, new GregorianCalendar(2003, 1, 1),
                                      new GregorianCalendar(2003, 2, 1),
                                      "4 Weeks, 0 Days, 0 Hours, 0 Mins, 0 Secs"),
                                  new GetTimeTextUseCase(5, Calendar.YEAR, Calendar.MILLISECOND, "now", "",
                                      unitsArray, new GregorianCalendar(2004, 1, 1),
                                      new GregorianCalendar(2004, 2, 1),
                                      "4 Weeks, 1 Day, 0 Hours, 0 Mins, 0 Secs"),
                                  new GetTimeTextUseCase(5, Calendar.MONTH, Calendar.MILLISECOND, "now", "",
                                      unitsArray, new GregorianCalendar(1990, 0, 1), /* 7 * 12 should be 84 */
                                      new GregorianCalendar(1997, 0, 1),
                                      "85 Months, 1 Week, 0 Days, 0 Hours, 0 Mins"),
                                  new GetTimeTextUseCase(5, Calendar.DATE, Calendar.MILLISECOND, "now", "",
                                      unitsArray,
                                      new GregorianCalendar(2004, 3, 3, 10,
                                          0), /* Daylight savings is in month '3' */
                                      new GregorianCalendar(2004, 3, 4, 11, 0),
                                      "1 Day, 0 Hours, 0 Mins, 0 Secs, 0 Millis")};
}
 
Example 19
/**
 * Test DateUtils.truncate()-method with Calendar.SECOND
 * 
 * @throws Exception
 * @since 3.0
 */
@Test
public void testTruncateMilliSecond() throws Exception {
    final int calendarField = Calendar.MILLISECOND;
    baseTruncateTest(targetMilliSecondDate, targetMilliSecondDate, calendarField);
}
 
Example 20
/**
 * Test DateUtils.truncate()-method with Calendar.SECOND
 * 
 * @throws Exception
 * @since 3.0
 */
@Test
public void testTruncateMilliSecond() throws Exception {
    final int calendarField = Calendar.MILLISECOND;
    baseTruncateTest(targetMilliSecondDate, targetMilliSecondDate, calendarField);
}