Java Code Examples for java.util.Calendar#MONTH

The following examples show how to use java.util.Calendar#MONTH . 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: PathResolver.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@ElFunction(name = "every")
public static int every(@ElParam("value") int value, @ElParam("unit") int unit) {
  switch (unit){
    case Calendar.YEAR:
    case Calendar.MONTH:
    case Calendar.DAY_OF_MONTH:
    case Calendar.HOUR_OF_DAY:
    case Calendar.MINUTE:
    case Calendar.SECOND:
      ELEval.getVariablesInScope().getContextVariable(TIME_INCREMENT_VALUE);
      break;
    default:
      throw new IllegalArgumentException(Utils.format("Invalid Calendar unit ordinal '{}'", unit));
  }
  return 0;
}
 
Example 2
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 3
Source File: DateMatch.java    From OsmGo with MIT License 6 votes vote down vote up
/**
 * Postpone trigger if first schedule matches the past
 */
private long postponeTriggerIfNeeded(Calendar current, Calendar next) {
  int currentYear = current.get(Calendar.YEAR);
  if (matchesUnit(Calendar.YEAR, current, next)) {
    next.set(Calendar.YEAR, currentYear + 1);
    this.unit = Calendar.YEAR;
  } else if (matchesUnit(Calendar.MONTH, current, next)) {
    next.set(Calendar.YEAR, currentYear + 1);
    this.unit = Calendar.MONTH;
  } else if (matchesUnit(Calendar.DAY_OF_MONTH, current, next)) {
    next.set(Calendar.MONTH, current.get(Calendar.MONTH) + 1);
    this.unit = Calendar.DAY_OF_MONTH;
  } else if (matchesUnit(Calendar.HOUR_OF_DAY, current, next)) {
    next.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) + 1);
    this.unit = Calendar.DAY_OF_MONTH;
  } else if (matchesUnit(Calendar.MINUTE, current, next)) {
    next.set(Calendar.HOUR_OF_DAY, current.get(Calendar.HOUR_OF_DAY) + 1);
    this.unit = Calendar.MINUTE;
  }
  return next.getTimeInMillis();
}
 
Example 4
Source File: LocalDateSpinnerModel.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Override
public Object getNextValue() {
	LocalDate nextDate = null;
	switch (calendarField) {
		case Calendar.DAY_OF_MONTH:
			nextDate = currentValue.plusDays(1);
			break;
		case Calendar.MONTH:
			nextDate = currentValue.plusMonths(1);
			break;
		case Calendar.YEAR:
			nextDate = currentValue.plusYears(1);
			break;
	}
	if (minDate != null && minDate.compareTo(nextDate) < 0) {
		return nextDate;
	}
	return null;
}
 
Example 5
Source File: LinearScaleTicks.java    From nebula with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Given min, max and the gridStepHint, returns the time grid step as a
 * double.
 *
 * @param min
 *            minimum value
 * @param max
 *            maximum value
 * @param gridStepHint
 * @return time rounded value
 */
private double getTimeGridStep(double min, double max, double gridStepHint) {
	// by default, make the least step to be minutes
	long timeStep;
	if (max - min < 1000) // <1 sec, step = 10 ms
		timeStep = 10l;
	else if (max - min < 60000) // < 1 min, step = 1 sec
		timeStep = 1000l;
	else if (max - min < 600000) // < 10 min, step = 10 sec
		timeStep = 10000l;
	else if (max - min < 6400000) // < 2 hour, step = 1 min
		timeStep = 60000l;
	else if (max - min < 43200000) // < 12 hour, step = 10 min
		timeStep = 600000l;
	else if (max - min < 86400000) // < 24 hour, step = 30 min
		timeStep = 1800000l;
	else if (max - min < 604800000) // < 7 days, step = 1 hour
		timeStep = 3600000l;
	else
		timeStep = 86400000l;

	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;
}
 
Example 6
Source File: Dates.java    From howsun-javaee-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 获取某时间的开始毫秒数
 *
 * @param calendar 时间
 * @param calendarField 类型,只支持年开始的秒数,月开始的秒数,日开始的秒数,小时开始的秒数,分钟开始的秒数
 * @return 毫秒数
 */
public static long getSecoendOfBegin(Calendar calendar, int calendarField){

	Calendar cal = calendar == null ? Calendar.getInstance() : (Calendar)calendar.clone();
	cal.set(Calendar.AM_PM, 0);

	switch (calendarField) {
		case Calendar.YEAR:
			cal.set(cal.get(Calendar.YEAR), 0, 1, 0, 0, 0);
		break;
		case Calendar.MONTH:
			cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 1, 0, 0, 0);
			break;
		case Calendar.DATE:
			cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), 0, 0, 0);
			break;
		case Calendar.HOUR:
			cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE),  cal.get(Calendar.HOUR), 0, 0);
			break;
		case Calendar.MINUTE:
			cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE),  cal.get(Calendar.HOUR), cal.get(Calendar.MINUTE), 0);
			break;
	default:
		throw new RuntimeException("不支持的时间模式。");
	}

	cal.set(Calendar.MILLISECOND, 0);

	return cal.getTimeInMillis();
}
 
Example 7
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 8
Source File: DateTimeTextProvider.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the text for the specified chrono, field, locale and style
 * for the purpose of formatting.
 * <p>
 * The text associated with the value is returned.
 * The null return value should be used if there is no applicable text, or
 * if the text would be a numeric representation of the value.
 *
 * @param chrono  the Chronology to get text for, not null
 * @param field  the field to get text for, not null
 * @param value  the field value to get text for, not null
 * @param style  the style to get text for, not null
 * @param locale  the locale to get text for, not null
 * @return the text for the field value, null if no text found
 */
public String getText(Chronology chrono, TemporalField field, long value,
                                TextStyle style, Locale locale) {
    if (chrono == IsoChronology.INSTANCE
            || !(field instanceof ChronoField)) {
        return getText(field, value, style, locale);
    }

    int fieldIndex;
    int fieldValue;
    if (field == ERA) {
        fieldIndex = Calendar.ERA;
        if (chrono == JapaneseChronology.INSTANCE) {
            if (value == -999) {
                fieldValue = 0;
            } else {
                fieldValue = (int) value + 2;
            }
        } else {
            fieldValue = (int) value;
        }
    } else if (field == MONTH_OF_YEAR) {
        fieldIndex = Calendar.MONTH;
        fieldValue = (int) value - 1;
    } else if (field == DAY_OF_WEEK) {
        fieldIndex = Calendar.DAY_OF_WEEK;
        fieldValue = (int) value + 1;
        if (fieldValue > 7) {
            fieldValue = Calendar.SUNDAY;
        }
    } else if (field == AMPM_OF_DAY) {
        fieldIndex = Calendar.AM_PM;
        fieldValue = (int) value;
    } else {
        return null;
    }
    return CalendarDataUtility.retrieveJavaTimeFieldValueName(
            chrono.getCalendarType(), fieldIndex, fieldValue, style.toCalendarStyle(), locale);
}
 
Example 9
Source File: Cardumen_0025_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Get the short and long values displayed for a field
 * @param field The field of interest
 * @return A sorted array of the field key / value pairs
 */
KeyValue[] getDisplayNames(int field) {
    Integer fieldInt = Integer.valueOf(field);
    KeyValue[] fieldKeyValues= nameValues.get(fieldInt);
    if(fieldKeyValues==null) {
        DateFormatSymbols symbols= DateFormatSymbols.getInstance(locale);
        switch(field) {
        case Calendar.ERA:
            // DateFormatSymbols#getEras() only returns AD/BC or translations
            // It does not work for the Thai Buddhist or Japanese Imperial calendars.
            // see: https://issues.apache.org/jira/browse/TRINIDAD-2126
            Calendar c = Calendar.getInstance(locale);
            // N.B. Some calendars have different short and long symbols, e.g. ja_JP_JP
            String[] shortEras = toArray(c.getDisplayNames(Calendar.ERA, Calendar.SHORT, locale));
            String[] longEras = toArray(c.getDisplayNames(Calendar.ERA, Calendar.LONG, locale));
            fieldKeyValues= createKeyValues(longEras, shortEras);
            break;
        case Calendar.DAY_OF_WEEK:
            fieldKeyValues= createKeyValues(symbols.getWeekdays(), symbols.getShortWeekdays());
            break;
        case Calendar.AM_PM:
            fieldKeyValues= createKeyValues(symbols.getAmPmStrings(), null);
            break;
        case Calendar.MONTH:
            fieldKeyValues= createKeyValues(symbols.getMonths(), symbols.getShortMonths());
            break;
        default:
            throw new IllegalArgumentException("Invalid field value "+field);
        }
        KeyValue[] prior = nameValues.putIfAbsent(fieldInt, fieldKeyValues);
        if(prior!=null) {
            fieldKeyValues= prior;
        }
    }
    return fieldKeyValues;
}
 
Example 10
Source File: FastDateParser.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private static String[] getDisplayNameArray(int field, boolean isLong, Locale locale) {
    DateFormatSymbols dfs = new DateFormatSymbols(locale);
    switch (field) {
        case Calendar.AM_PM:
            return dfs.getAmPmStrings();
        case Calendar.DAY_OF_WEEK:
            return isLong ? dfs.getWeekdays() : dfs.getShortWeekdays();
        case Calendar.ERA:
            return dfs.getEras();
        case Calendar.MONTH:
            return isLong ? dfs.getMonths() : dfs.getShortMonths();
    }
    return null;
}
 
Example 11
Source File: DateUtilsRoundingTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Tests DateUtils.round()-method with Calendar.MONTH
 * Includes rounding months with 28, 29, 30 and 31 days
 * Includes rounding to January 1
 * 
 * @throws Exception
 * @since 3.0
 */
@Test
public void testRoundMonth() throws Exception {
    final int calendarField = Calendar.MONTH;
    Date roundedUpDate, roundedDownDate, lastRoundedDownDate;
    Date minDate, maxDate;
    
    //month with 28 days
    roundedUpDate = dateTimeParser.parse("March 1, 2007 0:00:00.000");
    roundedDownDate = dateTimeParser.parse("February 1, 2007 0:00:00.000");
    lastRoundedDownDate = dateTimeParser.parse("February 14, 2007 23:59:59.999");
    baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate,  calendarField);

    //month with 29 days
    roundedUpDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
    roundedDownDate = dateTimeParser.parse("February 1, 2008 0:00:00.000");
    lastRoundedDownDate = dateTimeParser.parse("February 15, 2008 23:59:59.999");
    baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate,  calendarField);
    
    //month with 30 days
    roundedUpDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
    roundedDownDate = dateTimeParser.parse("April 1, 2008 0:00:00.000");
    lastRoundedDownDate = dateTimeParser.parse("April 15, 2008 23:59:59.999");
    baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate,  calendarField);
    
    //month with 31 days
    roundedUpDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
    roundedDownDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
    lastRoundedDownDate = dateTimeParser.parse("May 16, 2008 23:59:59.999");
    baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate,  calendarField);
    
    //round to January 1
    minDate = dateTimeParser.parse("December 17, 2007 00:00:00.000");
    maxDate = dateTimeParser.parse("January 16, 2008 23:59:59.999");
    roundToJanuaryFirst(minDate, maxDate, calendarField);
}
 
Example 12
Source File: DateUtil.java    From zone-sdk with MIT License 5 votes vote down vote up
/**
 * 只有月份 从0开始 所以少1,其他都是正常的 (设置1  其实是2)
 * 防Month坑方法
 * @param calendar
 * @param field
 * @param value
 */
public static void set(Calendar calendar, int field, int value) {
    if (Calendar.MONTH == field) {
        calendar.set(field, value - 1);
    } else
        calendar.set(field, value);

}
 
Example 13
Source File: DBDate.java    From evosql with Apache License 2.0 5 votes vote down vote up
@Override
public String mutate(String currentValue, boolean nullable) {
	// If null, generate a new value that is not null, if not null generate null with probability
	if(currentValue == null)
		return generateRandom(false);
	else if(nullable && random.nextDouble() < EvoSQLConfiguration.MUTATE_NULL_PROBABIBLITY)
		return null;
	
	Calendar cal = Calendar.getInstance();
	try {
		cal.setTimeInMillis(format.parse(currentValue).getTime());
	} catch (ParseException e) {
		throw new RuntimeException(e);
	}

	for (int i : genetic.Instrumenter.DATE_CONSTANTS) {
		if (random.nextDouble() <= probability) {
			int val;
			switch (i) {
				case Calendar.YEAR: val = cal.get(Calendar.YEAR); break;
				case Calendar.MONTH: val = cal.get(Calendar.MONTH); break;
				case Calendar.DAY_OF_MONTH: val = cal.get(Calendar.DAY_OF_MONTH); break;		
				default: throw new RuntimeException("Impossible value " + i);
			}
			val = (int)(val + (random.nextSignedDouble() * 10));
			switch (i) {
				case Calendar.YEAR: cal.set(Calendar.YEAR, val); break;
				case Calendar.MONTH: cal.set(Calendar.MONTH, val); break;
				case Calendar.DAY_OF_MONTH: cal.set(Calendar.DAY_OF_MONTH, val); break;		
			}
		}
	}
	
	return format.format(cal.getTime());
}
 
Example 14
Source File: MainActivity.java    From ActivityDiary with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
    super.onQueryComplete(token, cookie, cursor);
    if ((cursor != null) && cursor.moveToFirst()) {
        if (token == QUERY_CURRENT_ACTIVITY_STATS) {
            long avg = cursor.getLong(cursor.getColumnIndex(ActivityDiaryContract.DiaryActivity.X_AVG_DURATION));
            viewModel.mAvgDuration.setValue(getResources().
                    getString(R.string.avg_duration_description, TimeSpanFormatter.format(avg)));

            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext());
            String formatString = sharedPref.getString(SettingsActivity.KEY_PREF_DATETIME_FORMAT,
                    getResources().getString(R.string.default_datetime_format));

            long start = cursor.getLong(cursor.getColumnIndex(ActivityDiaryContract.DiaryActivity.X_START_OF_LAST));

            viewModel.mStartOfLast.setValue(getResources().
                    getString(R.string.last_done_description, DateFormat.format(formatString, start)));

        }else if(token == QUERY_CURRENT_ACTIVITY_TOTAL) {
            StatParam p = (StatParam)cookie;
            long total = cursor.getLong(cursor.getColumnIndex(ActivityDiaryContract.DiaryStats.DURATION));

            String x = DateHelper.dateFormat(p.field).format(p.end);
            x = x + ": " + TimeSpanFormatter.format(total);
            switch(p.field){
                case Calendar.DAY_OF_YEAR:
                    viewModel.mTotalToday.setValue(x);
                    break;
                case Calendar.WEEK_OF_YEAR:
                    viewModel.mTotalWeek.setValue(x);
                    break;
                case Calendar.MONTH:
                    viewModel.mTotalMonth.setValue(x);
                    break;
            }
        }
    }
}
 
Example 15
Source File: Cardumen_0096_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Get the short and long values displayed for a field
 * @param field The field of interest
 * @return A sorted array of the field key / value pairs
 */
KeyValue[] getDisplayNames(int field) {
    Integer fieldInt = Integer.valueOf(field);
    KeyValue[] fieldKeyValues= nameValues.get(fieldInt);
    if(fieldKeyValues==null) {
        DateFormatSymbols symbols= DateFormatSymbols.getInstance(locale);
        switch(field) {
        case Calendar.ERA:
            // DateFormatSymbols#getEras() only returns AD/BC or translations
            // It does not work for the Thai Buddhist or Japanese Imperial calendars.
            // see: https://issues.apache.org/jira/browse/TRINIDAD-2126
            Calendar c = Calendar.getInstance(locale);
            // N.B. Some calendars have different short and long symbols, e.g. ja_JP_JP
            String[] shortEras = toArray(c.getDisplayNames(Calendar.ERA, Calendar.SHORT, locale));
            String[] longEras = toArray(c.getDisplayNames(Calendar.ERA, Calendar.LONG, locale));
            fieldKeyValues= createKeyValues(longEras, shortEras);
            break;
        case Calendar.DAY_OF_WEEK:
            fieldKeyValues= createKeyValues(symbols.getWeekdays(), symbols.getShortWeekdays());
            break;
        case Calendar.AM_PM:
            fieldKeyValues= createKeyValues(symbols.getAmPmStrings(), null);
            break;
        case Calendar.MONTH:
            fieldKeyValues= createKeyValues(symbols.getMonths(), symbols.getShortMonths());
            break;
        default:
            throw new IllegalArgumentException("Invalid field value "+field);
        }
        KeyValue[] prior = nameValues.putIfAbsent(fieldInt, fieldKeyValues);
        if(prior!=null) {
            fieldKeyValues= prior;
        }
    }
    return fieldKeyValues;
}
 
Example 16
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 17
Source File: Task.java    From jdotxt with GNU General Public License v3.0 4 votes vote down vote up
private void init(String rawText, Date defaultPrependedDate) {
	TextSplitter splitter = TextSplitter.getInstance();
	TextSplitter.SplitResult splitResult = splitter.split(rawText);
	this.priority = splitResult.priority;
	this.text = splitResult.text;
	this.prependedDate = splitResult.prependedDate;
	this.completed = splitResult.completed;
	this.completionDate = splitResult.completedDate;

	this.contexts = ContextParser.getInstance().parse(text);
	this.projects = ProjectParser.getInstance().parse(text);
	this.mailAddresses = MailAddressParser.getInstance().parse(text);
	this.links = LinkParser.getInstance().parse(text);
	this.phoneNumbers = PhoneNumberParser.getInstance().parse(text);
	this.deleted = Strings.isEmptyOrNull(text);
	this.hidden = HiddenParser.getInstance().parse(text);
	this.thresholdDate = ThresholdDateParser.getInstance().parseThresholdDate(rawText);
	this.dueDate = ThresholdDateParser.getInstance().parseDueDate(rawText);
	String[] parsedRec = RecParser.getInstance().parse(rawText);

	rec = parsedRec != null;
	if (rec) {
		isFromThreshold = !(parsedRec[0].isEmpty());
		amount = Integer.parseInt(parsedRec[1]);
		if ("d".equals(parsedRec[2])) {
			duration = Calendar.DAY_OF_YEAR;
		} else if ("w".equals(parsedRec[2])) {
			duration = Calendar.WEEK_OF_YEAR;
		} else if ("m".equals(parsedRec[2])) {
			duration = Calendar.MONTH;
		} else if ("y".equals(parsedRec[2])) {
			duration = Calendar.YEAR;
		}
	}

	if (defaultPrependedDate != null
			&& Strings.isEmptyOrNull(this.prependedDate)) {
		SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
		this.prependedDate = formatter.format(defaultPrependedDate);
	}

	if (!Strings.isEmptyOrNull(this.prependedDate)) {
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
		try {
			Date d = sdf.parse(this.prependedDate);
			this.relativeAge = RelativeDate.getRelativeDate(d);
		} catch (ParseException e) {
			// e.printStackTrace();
		}
	}
}
 
Example 18
Source File: DateRangePrefixTree.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/** Calendar utility method consistent with {@link java.time.format.DateTimeFormatter#ISO_INSTANT} except
 * has no trailing 'Z', and will be truncated to the units given according to
 * {@link Calendar#isSet(int)}.
 * A fully cleared calendar will yield the string "*".
 * The isSet() state of the Calendar is re-instated when done. */
public String toString(Calendar cal) {
  final int calPrecField = getCalPrecisionField(cal);//must call first; getters set all fields
  if (calPrecField == -1)
    return "*";
  try {
    StringBuilder builder = new StringBuilder("yyyy-MM-dd'T'HH:mm:ss.SSS".length());//typical
    int year = cal.get(Calendar.YEAR); // within the era (thus always positve).  >= 1.
    if (cal.get(Calendar.ERA) == 0) { // BC
      year -= 1; // 1BC should be "0000", so shift by one
      if (year > 0) {
        builder.append('-');
      }
    } else if (year > 9999) {
      builder.append('+');
    }
    appendPadded(builder, year, (short) 4);
    if (calPrecField >= Calendar.MONTH) {
      builder.append('-');
      appendPadded(builder, cal.get(Calendar.MONTH) + 1, (short) 2); // +1 since first is 0
    }
    if (calPrecField >= Calendar.DAY_OF_MONTH) {
      builder.append('-');
      appendPadded(builder, cal.get(Calendar.DAY_OF_MONTH), (short) 2);
    }
    if (calPrecField >= Calendar.HOUR_OF_DAY) {
      builder.append('T');
      appendPadded(builder, cal.get(Calendar.HOUR_OF_DAY), (short) 2);
    }
    if (calPrecField >= Calendar.MINUTE) {
      builder.append(':');
      appendPadded(builder, cal.get(Calendar.MINUTE), (short) 2);
    }
    if (calPrecField >= Calendar.SECOND) {
      builder.append(':');
      appendPadded(builder, cal.get(Calendar.SECOND), (short) 2);
    }
    if (calPrecField >= Calendar.MILLISECOND && cal.get(Calendar.MILLISECOND) > 0) { // only if non-zero
      builder.append('.');
      appendPadded(builder,  cal.get(Calendar.MILLISECOND), (short) 3);
    }

    return builder.toString();
  } finally {
    clearFieldsAfter(cal, calPrecField);//restore precision state modified by get()
  }
}
 
Example 19
Source File: StatisticsActivity.java    From ActivityDiary with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    currentDateTime = new Date().getTime();
    Bundle bnd = new Bundle();
    switch (position) {
        case 0: // all
            break;
        case 1: // last 7 days
            bnd.putLong("start", currentDateTime - (1000 * 60 * 60 * 24 * 7));
            bnd.putLong("end", currentDateTime);
            break;
        case 2: // last 30 days
            bnd.putLong("start", currentDateTime - (1000 * 60 * 60 * 24 * 7 * 30));
            bnd.putLong("end", currentDateTime);
            break;
        case 3: // Day
            currentOffset = 0;
            currentRange = Calendar.DAY_OF_YEAR;
            loadRange(currentRange, currentOffset);
            break;
        case 4: // week
            currentOffset = 0;
            currentRange = Calendar.WEEK_OF_YEAR;
            loadRange(currentRange, currentOffset);
            break;
        case 5: // month
            currentOffset = 0;
            currentRange = Calendar.MONTH;
            loadRange(currentRange, currentOffset);
            break;
        case 6: // year
            currentOffset = 0;
            currentRange = Calendar.YEAR;
            loadRange(currentRange, currentOffset);
            break;
        default:
    }
    if(position < 3){
        rangeTextView.setVisibility(View.INVISIBLE);
        rangeEarlierImageView.setVisibility(View.INVISIBLE);
        rangeLaterImageView.setVisibility(View.INVISIBLE);
    }else{
        rangeTextView.setVisibility(View.VISIBLE);
        rangeEarlierImageView.setVisibility(View.VISIBLE);
        rangeLaterImageView.setVisibility(View.VISIBLE);
    }
    if(position < 1) {
        getLoaderManager().restartLoader(LOADER_ID_TIME, bnd, this);
    }else if(position < 3){
        getLoaderManager().restartLoader(LOADER_ID_RANGE, bnd, this);
    }
}
 
Example 20
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;
    }