Java Code Examples for java.util.Calendar

The following are top voted examples for showing how to use java.util.Calendar. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: my-ministry-assistant   File: TitleAndDateAdapter.java View source code 7 votes vote down vote up
public void addItem(int id, String title, String date) {
	Calendar convertedDate = Calendar.getInstance(Locale.getDefault());
	if(!TextUtils.isEmpty(date)) {
		try {
			convertedDate.setTime(TimeUtils.dbDateFormat.parse(date));
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	addItem(new ItemWithDate(id, title, !TextUtils.isEmpty(date) ? createDisplayDate(convertedDate) : context.getResources().getString(R.string.no_activity)));
}
 
Example 2
Project: my-ministry-assistant   File: DBBackupsListFragment.java View source code 6 votes vote down vote up
private void createBackup() {
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss-aaa", Locale.getDefault());
Calendar now = Calendar.getInstance();
String date = dateFormatter.format(now.getTime()).toString();
File intDB = getActivity().getApplicationContext().getDatabasePath(MinistryDatabase.DATABASE_NAME);
File extDB = FileUtils.getExternalDBFile(getActivity().getApplicationContext(), date + ".db");

try {
	if(extDB != null) {
		if(!extDB.exists())
			extDB.createNewFile();
		
		FileUtils.copyFile(intDB, extDB);
		
		reloadAdapter();
		
		Toast.makeText(getActivity(), getActivity().getApplicationContext().getString(R.string.toast_export_text), Toast.LENGTH_SHORT).show();
	}
} catch (IOException e) {
	Toast.makeText(getActivity(), getActivity().getApplicationContext().getString(R.string.toast_export_text_error), Toast.LENGTH_SHORT).show();
}
  }
 
Example 3
Project: my-ministry-assistant   File: Helper.java View source code 6 votes vote down vote up
public static Calendar roundMinutesAndHour(Calendar time, int TIME_PICKER_INTERVAL) {
	int minute = time.get(Calendar.MINUTE);
	int hour = time.get(Calendar.HOUR_OF_DAY);
	
	if (time.get(Calendar.MINUTE) % TIME_PICKER_INTERVAL != 0) {
		int minuteFloor = minute - (minute % TIME_PICKER_INTERVAL);
		minute = minuteFloor + (minute == minuteFloor + 1 ? TIME_PICKER_INTERVAL : 0);
		if (minute == 60) {
			hour++;
			minute = 0;
		}
	}
	
	time.set(Calendar.HOUR_OF_DAY, hour);
	time.set(Calendar.MINUTE, minute);
	return time;
}
 
Example 4
Project: my-ministry-assistant   File: HelpUtils.java View source code 6 votes vote down vote up
public static void setWeeklyAlarm(Context context) {
	Calendar time = Calendar.getInstance(Locale.getDefault());
	int year = time.get(Calendar.YEAR);
	int month = time.get(Calendar.MONTH);
	int day = time.get(Calendar.DAY_OF_MONTH);
	int weekday = PrefUtils.getDBBackupWeeklyWeekday(context);
	
	try {
		time.setTime(DateFormat.getTimeFormat(context).parse(PrefUtils.getDBBackupWeeklyTime(context)));
	} catch (ParseException e) {
		e.printStackTrace();
	}
	
	time.set(year, month, day);
	
	while(true) {
		if(time.get(Calendar.DAY_OF_WEEK) == weekday)
			break;
		
		time.add(Calendar.DAY_OF_MONTH, 1);
	}
	
	int alarmType = AlarmManager.RTC;
	long interval = AlarmManager.INTERVAL_DAY * 7;
	//long start = time.getTimeInMillis() + interval;
	long start = time.getTimeInMillis();
	
	PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, WeeklyBackupService.class), PendingIntent.FLAG_UPDATE_CURRENT);
   	AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
   	am.setInexactRepeating(alarmType, start, interval, pi);
}
 
Example 5
Project: jentrata-msh   File: SchedulerTask.java View source code 6 votes vote down vote up
public static Date getNextRunDateFromNow(int day_of_week, int hour, int min, int sec) {

			// get an instance of the calendar
			Calendar newTime = GregorianCalendar.getInstance();
			int dif = day_of_week - newTime.get(Calendar.DAY_OF_WEEK);
			if (dif < 0) {
				dif = 7 + dif;
			}

			if (dif == 0) {
				if (hour < newTime.get(Calendar.HOUR_OF_DAY)
						|| min < newTime.get(Calendar.MINUTE)
						|| sec < newTime.get(Calendar.SECOND)) {
					dif = 7 + dif;
				} else {
				}
			}

			// add the difference of days
			newTime.add(Calendar.DATE, dif);
			// set the time
			newTime.set(Calendar.HOUR_OF_DAY, hour);
			newTime.set(Calendar.MINUTE, min);
			newTime.set(Calendar.SECOND, sec);

			return newTime.getTime();
	}
 
Example 6
Project: jentrata-msh   File: EbmsUtilityTest.java View source code 6 votes vote down vote up
/**
 * Test for converting from GMT datetime representation to java date object.  
 */
public void testGMT2Date_Pos0() throws Exception {
	
	Date date 	 = new Date();		
	
	String dateTime = date.toString();
	
	Date convertedDate = EbmsUtility.GMT2Date(dateTime);
	
	System.out.println("GMT converted: " + convertedDate);
	
	// Since the millisecond pecision will be lost during conversion.
	// we need to create a calendar and set the millisecond to zero. 
	Calendar cal = Calendar.getInstance();		
	cal.setTimeInMillis(date.getTime());
	cal.set(Calendar.MILLISECOND, 0);
	
	// Check whether the time is equal or not. 
	TestCase.assertEquals(convertedDate.getTime(), cal.getTimeInMillis());
}
 
Example 7
Project: my-ministry-assistant   File: HelpUtils.java View source code 6 votes vote down vote up
public static void setDailyAlarm(Context context) {
	Calendar time = Calendar.getInstance(Locale.getDefault());
	int year = time.get(Calendar.YEAR);
	int month = time.get(Calendar.MONTH);
	int day = time.get(Calendar.DAY_OF_MONTH);
	
	try {
		time.setTime(DateFormat.getTimeFormat(context).parse(PrefUtils.getDBBackupDailyTime(context)));
	} catch (ParseException e) {
		e.printStackTrace();
	}
	
	time.set(year, month, day);
	
	int alarmType = AlarmManager.RTC;
	long interval = AlarmManager.INTERVAL_DAY;
	//long start = time.getTimeInMillis() + interval;
	long start = time.getTimeInMillis();
	
	PendingIntent pi = PendingIntent.getService(context, 0, new Intent(context, DailyBackupService.class), PendingIntent.FLAG_UPDATE_CURRENT);
   	AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
	am.setInexactRepeating(alarmType, start, interval, pi);
}
 
Example 8
Project: aipo   File: ProjectTaskSimpleSelectData.java View source code 6 votes vote down vote up
/**
 * ???????????????????????
 *
 * @return TRUE:????????
 */

public boolean isSunday(int days) {
  Calendar cal = (Calendar) calFrom.clone();
  cal.add(Calendar.DAY_OF_MONTH, days - 1);
  return Calendar.SUNDAY == cal.get(Calendar.DAY_OF_WEEK);
}
 
Example 9
Project: aipo   File: ProjectTaskSimpleSelectData.java View source code 6 votes vote down vote up
/**
 * ???????????????????????
 *
 * @return TRUE:????????
 */

public boolean isSaturday(int days) {
  Calendar cal = (Calendar) calFrom.clone();
  cal.add(Calendar.DAY_OF_MONTH, days - 1);
  return Calendar.SATURDAY == cal.get(Calendar.DAY_OF_WEEK);
}
 
Example 10
Project: jentrata-msh   File: SchedulerTask.java View source code 6 votes vote down vote up
/**
 * Checks to see whether the current time has exceeded the parameter 'time'.
 * 
 * @param time
 * @return
 * @throws Exception
 */
private boolean checkNotExceeded(String time) throws Exception {
	Calendar cur = GregorianCalendar.getInstance();
	Calendar upperLimit = GregorianCalendar.getInstance();
	try {
		Date lowerLimit = getDateFormat().parse(time);
		upperLimit.setTime(lowerLimit);
		upperLimit.add(Calendar.MINUTE, 1);
		return upperLimit.after(cur);
	} catch (ParseException e) {
		AdminError("Parse error when checking the start time.");
		throw new Exception("Parse error when checking the start time.", e);
	}
}
 
Example 11
Project: aipo   File: ALDateUtil.java View source code 6 votes vote down vote up
/**
 * ???????????????
 * 
 * @param cal
 * @return
 */
public static String getDayOfWeek(Calendar cal) {
  String res = "";

  switch (cal.get(Calendar.DAY_OF_WEEK)) {
    case Calendar.SUNDAY:
      res = ALLocalizationUtils.getl10n("COMMONS_UTILS_SUNDAY_CELL");
      break;
    case Calendar.MONDAY:
      res = ALLocalizationUtils.getl10n("COMMONS_UTILS_MONDAY_CELL");
      break;
    case Calendar.TUESDAY:
      res = ALLocalizationUtils.getl10n("COMMONS_UTILS_TUSEDAY_CELL");
      break;
    case Calendar.WEDNESDAY:
      res = ALLocalizationUtils.getl10n("COMMONS_UTILS_WEDNESDAY_CELL");
      break;
    case Calendar.THURSDAY:
      res = ALLocalizationUtils.getl10n("COMMONS_UTILS_THURSDAY_CELL");
      break;
    case Calendar.FRIDAY:
      res = ALLocalizationUtils.getl10n("COMMONS_UTILS_FRIDAY_CELL");
      break;
    case Calendar.SATURDAY:
      res = ALLocalizationUtils.getl10n("COMMONS_UTILS_SATURDAY_CELL");
      break;
    default:
      return null;
  }
  return res;
}
 
Example 12
Project: aipo   File: ALDateUtil.java View source code 6 votes vote down vote up
/**
 * ??????????????
 * 
 * @param month
 * @return
 */
public static String getStringMonth(int month) {
  switch (month) {
    case Calendar.JANUARY:
      return "01";
    case Calendar.FEBRUARY:
      return "02";
    case Calendar.MARCH:
      return "03";
    case Calendar.APRIL:
      return "04";
    case Calendar.MAY:
      return "05";
    case Calendar.JUNE:
      return "06";
    case Calendar.JULY:
      return "07";
    case Calendar.AUGUST:
      return "08";
    case Calendar.SEPTEMBER:
      return "09";
    case Calendar.OCTOBER:
      return "10";
    case Calendar.NOVEMBER:
      return "11";
    case Calendar.DECEMBER:
      return "12";
    default:
      return null;
  }
}
 
Example 13
Project: aipo   File: EventlogUtils.java View source code 6 votes vote down vote up
/**
 * @param start_end
 *          true=>start, false =>end
 * @param rundata
 * @param context
 * @return
 */
public static Calendar getViewCalendar(boolean start_end, RunData rundata,
    Context context) {
  Calendar cal = Calendar.getInstance();
  cal.set(Calendar.HOUR_OF_DAY, 0);
  cal.set(Calendar.MINUTE, 0);
  cal.set(Calendar.SECOND, 0);
  if (start_end) {
    cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);
  }
  int[] par = { Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH };
  String[] str = { "_date_year", "_date_month", "_date_day" };
  String head = (start_end) ? "start" : "end";
  for (int i = 0; i < str.length; i++) {
    str[i] = head.concat(str[i]);
    setCalendar(cal, par[i], str[i], rundata, context);
  }
  return cal;
}
 
Example 14
Project: FriendlyAlarmClock   File: AlarmsFragment.java View source code 6 votes vote down vote up
private void addToAlarmManager(AlarmModel alarm) {
	Calendar cur = Calendar.getInstance();
	
	Calendar cal = Calendar.getInstance();
	cal.set(Calendar.HOUR_OF_DAY, alarm.getHour());
	cal.set(Calendar.MINUTE, alarm.getMinute());

	if (cal.before(cur)) {
		cal.roll(Calendar.DAY_OF_YEAR, true);
	}

	Intent intent = new Intent(getActivity(), AlarmReceiver.class);
	intent.putExtra("assoc_pid", String.valueOf(alarm.getPid()));

	PendingIntent sender = PendingIntent.getBroadcast(getActivity(),
			AlarmReceiver.REQUEST_CODE, intent,
			PendingIntent.FLAG_UPDATE_CURRENT);

	// Get the AlarmManager service
	AlarmManager am = (AlarmManager) getActivity().getSystemService(
			Context.ALARM_SERVICE);
	am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

	long diff = cal.getTimeInMillis() - cur.getTimeInMillis();
	int hours = (int) ((diff / (1000 * 60 * 60)) % 24);
	int minutes = (int) ((diff / (1000 * 60)) % 60);
	
	Toast.makeText(getActivity(),
			String.format("This alarm is set for %d hours and %d minutes from now.", hours, minutes),
			Toast.LENGTH_LONG).show();
}
 
Example 15
Project: aipo   File: ALDateContainer.java View source code 6 votes vote down vote up
/**
 * ???????????
 * 
 * @return
 * @throws NumberFormatException
 * @throws ALIllegalDateException
 */
public Date getDate() throws NumberFormatException, ALIllegalDateException {
  if (date != null) {
    return (Date) date.clone();
  }

  int yearNum = getYear();
  int monthNum = getMonth() - 1;
  int dayNum = getDay();

  try {
    Calendar calendar = new GregorianCalendar(yearNum, monthNum, dayNum);

    calendar.setLenient(false);
    date = calendar.getTime();
    return (Date) date.clone();
  } catch (IllegalArgumentException ex) {
    throw new ALIllegalDateException("Year = "
      + year
      + ", Month = "
      + month
      + ", Day = "
      + day);
  }
}
 
Example 16
Project: nmonvisualizer   File: AbsoluteTimeIntervalPanel.java View source code 6 votes vote down vote up
@Override
public void propertyChange(PropertyChangeEvent evt) {
    if ("timeZone".equals(evt.getPropertyName())) {
        TimeZone timeZone = (TimeZone) evt.getNewValue();

        DateEditor de = (DateEditor) start.getEditor();
        de.getFormat().setTimeZone(timeZone);

        // hack to get the spinner to fire a state change and update the displayed value
        ((SpinnerDateModel) start.getModel()).setCalendarField(Calendar.MINUTE);
        ((SpinnerDateModel) start.getModel()).setCalendarField(Calendar.SECOND);

        de = (DateEditor) end.getEditor();
        de.getFormat().setTimeZone(timeZone);

        ((SpinnerDateModel) end.getModel()).setCalendarField(Calendar.MINUTE);
        ((SpinnerDateModel) end.getModel()).setCalendarField(Calendar.SECOND);
    }
}
 
Example 17
Project: smack-xmpp   File: Time.java View source code 6 votes vote down vote up
/**
 * Creates a new Time instance using the specified calendar instance as
 * the time value to send.
 *
 * @param cal the time value.
 */
public Time(Calendar cal) {
    TimeZone timeZone = cal.getTimeZone();
    tz = cal.getTimeZone().getID();
    display = displayFormat.format(cal.getTime());
    // Convert local time to the UTC time.
    utc = utcFormat.format(new Date(
            cal.getTimeInMillis() - timeZone.getOffset(cal.getTimeInMillis())));
}
 
Example 18
Project: Log-Cutter   File: AppConfig.java View source code 6 votes vote down vote up
private static final long parseDelay(String hhmm)
{
	long ts			= -1L;
	String[] tm		= hhmm.split(":");
	Calendar delay	= null;
	Calendar now	= Calendar.getInstance();
	
	now.set(Calendar.SECOND, 0);
	now.set(Calendar.MILLISECOND, 0);

	if(tm.length == 2)
	{
		int hour	= GeneralHelper.str2Int(tm[0], -1);
		int minute	= GeneralHelper.str2Int(tm[1], -1);
		
		if(hour >= 0 && minute >= 0)
		{
			delay = (Calendar)now.clone();
			delay.set(Calendar.HOUR_OF_DAY, hour);
			delay.set(Calendar.MINUTE, minute);
			
			if(delay.compareTo(now) < 0)
				delay.add(Calendar.DAY_OF_MONTH, 1);
		}
	}
	
	if(delay != null)
		ts = TimeUnit.MILLISECONDS.toMinutes(delay.getTimeInMillis() - now.getTimeInMillis());
	
	return ts;
}
 
Example 19
Project: flow-android   File: CalendarHelper.java View source code 6 votes vote down vote up
public static Calendar getCurrentWeek() {
    Calendar currentWeek = Calendar.getInstance();
    currentWeek.setFirstDayOfWeek(Calendar.MONDAY);
    currentWeek.set(Calendar.HOUR_OF_DAY, 0);
    currentWeek.clear(Calendar.MINUTE);
    currentWeek.clear(Calendar.SECOND);
    currentWeek.clear(Calendar.MILLISECOND);
    return currentWeek;
}
 
Example 20
Project: SOLR   File: DateMathParser.java View source code 6 votes vote down vote up
/**
 * Modifies the specified Calendar by "rounding" down to the specified unit
 *
 * @exception IllegalArgumentException if unit isn't recognized.
 * @see #CALENDAR_UNITS
 */
public static void round(Calendar c, String unit) {
  Integer uu = CALENDAR_UNITS.get(unit);
  if (null == uu) {
    throw new IllegalArgumentException("Rounding Unit not recognized: "
                                       + unit);
  }
  int u = uu.intValue();
  
  switch (u) {
    
  case Calendar.YEAR:
    c.clear(Calendar.MONTH);
    /* fall through */
  case Calendar.MONTH:
    c.clear(Calendar.DAY_OF_MONTH);
    c.clear(Calendar.DAY_OF_WEEK);
    c.clear(Calendar.DAY_OF_WEEK_IN_MONTH);
    c.clear(Calendar.DAY_OF_YEAR);
    c.clear(Calendar.WEEK_OF_MONTH);
    c.clear(Calendar.WEEK_OF_YEAR);
    /* fall through */
  case Calendar.DATE:
    c.clear(Calendar.HOUR_OF_DAY);
    c.clear(Calendar.HOUR);
    c.clear(Calendar.AM_PM);
    /* fall through */
  case Calendar.HOUR_OF_DAY:
    c.clear(Calendar.MINUTE);
    /* fall through */
  case Calendar.MINUTE:
    c.clear(Calendar.SECOND);
    /* fall through */
  case Calendar.SECOND:
    c.clear(Calendar.MILLISECOND);
    break;
  default:
    throw new IllegalStateException
      ("No logic for rounding value ("+u+") " + unit);
  }

}
 
Example 21
Project: aipo   File: ExtTimecardFormData.java View source code 6 votes vote down vote up
/**
 * ?????????
 *
 * @return
 */
public boolean getIsToday() {
  int change_hour =
    ExtTimecardUtils
      .getEipTExtTimecardSystemByUserId(login_uid)
      .getChangeHour();
  Calendar cal = Calendar.getInstance();
  Date date = punch_date.getValue();
  boolean is_today = false;
  if ((Calendar.getInstance().get(Calendar.HOUR_OF_DAY)) < change_hour) {
    Calendar tmp_cal = Calendar.getInstance();
    tmp_cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal
      .get(Calendar.DATE));
    is_today = ExtTimecardUtils.sameDay(date, tmp_cal.getTime());
  } else {
    is_today = ExtTimecardUtils.sameDay(date, cal.getTime());
  }
  return is_today;
}
 
Example 22
Project: queueing-simulation   File: WeekTests.java View source code 6 votes vote down vote up
/**
 * The first week in 2005 should span the range:
 *
 * TimeZone         | Start Millis  | End Millis    | Start Date  | End Date
 * -----------------+---------------+---------------+-------------+------------
 * Europe/London    | 1104710400000 | 1105315199999 |  3-Jan-2005 | 9-Jan-2005
 * Europe/Paris     | 1104706800000 | 1105311599999 |  3-Jan-2005 | 2-Jan-2005
 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005
 *
 * In London and Paris, Monday is the first day of the week, while in the
 * US it is Sunday.
 *
 * Previously, we were using these values, but see Java Bug ID 4960215:
 *
 * TimeZone         | Start Millis  | End Millis    | Start Date  | End Date
 * -----------------+---------------+---------------+-------------+------------
 * Europe/London    | 1104105600000 | 1104710399999 | 27-Dec-2004 | 2-Jan-2005
 * Europe/Paris     | 1104102000000 | 1104706799999 | 27-Dec-2004 | 2-Jan-2005
 * America/New_York | 1104037200000 | 1104641999999 | 26-Dec-2004 | 1-Jan-2005
 */
public void testWeek12005() {
    Week w1 = new Week(1, 2005);
    Calendar c1 = Calendar.getInstance(
            TimeZone.getTimeZone("Europe/London"), Locale.UK);
    c1.setMinimalDaysInFirstWeek(4);  // see Java Bug ID 4960215
    assertEquals(1104710400000L, w1.getFirstMillisecond(c1));
    assertEquals(1105315199999L, w1.getLastMillisecond(c1));
    Calendar c2 = Calendar.getInstance(
            TimeZone.getTimeZone("Europe/Paris"), Locale.FRANCE);
    c2.setMinimalDaysInFirstWeek(4);  // see Java Bug ID 4960215
    assertEquals(1104706800000L, w1.getFirstMillisecond(c2));
    assertEquals(1105311599999L, w1.getLastMillisecond(c2));
    Calendar c3 = Calendar.getInstance(
            TimeZone.getTimeZone("America/New_York"), Locale.US);
    assertEquals(1104037200000L, w1.getFirstMillisecond(c3));
    assertEquals(1104641999999L, w1.getLastMillisecond(c3));
}
 
Example 23
Project: Technomap   File: TimeLib.java View source code 6 votes vote down vote up
/**
 * Based on code posted at
 *  http://forum.java.sun.com/thread.jspa?threadID=488676&messageID=2292012
 */
private static int estimateUnitsBetween(long t0, long t1, int field) {
    long d = t1-t0;
    switch (field) {
    case Calendar.MILLISECOND:
        return (int)d; // this could be very inaccurate. TODO: use long instead of int?
    case Calendar.SECOND:
        return (int)(d / SECOND_MILLIS + .5);
    case Calendar.MINUTE:
        return (int)(d / MINUTE_MILLIS + .5);
    case Calendar.HOUR_OF_DAY:
    case Calendar.HOUR:
        return (int)(d / HOUR_MILLIS + .5);
    case Calendar.DAY_OF_WEEK_IN_MONTH :
    case Calendar.DAY_OF_MONTH :
    // case Calendar.DATE : // codes to same int as DAY_OF_MONTH
        return (int) (d / DAY_MILLIS + .5);
    case Calendar.WEEK_OF_YEAR :
        return (int) (d / WEEK_MILLIS + .5);
    case Calendar.MONTH :
        return (int) (d / MONTH_MILLIS + .5);
    case Calendar.YEAR :
        return (int) (d / YEAR_MILLIS + .5);
    case DECADE:
        return (int) (d / DECADE_MILLIS + .5);
    case CENTURY:
        return (int) (d / CENTURY_MILLIS + .5);
    case MILLENIUM:
        return (int) (d / MILLENIUM_MILLIS + .5);
    default:
        return 0;
    }
}
 
Example 24
Project: jena   File: TestDateTimeUtils.java View source code 6 votes vote down vote up
@Test
public void testCalendarToXSDDateTimeString_1() {
	Calendar cal = createCalendar(1984, Calendar.MARCH, 22, 14, 32, 1, 0, "Z") ;
	assertEquals("1984-03-22T14:32:01+00:00", DateTimeUtils.calendarToXSDDateTimeString(cal));
	cal.setTimeZone(TimeZone.getTimeZone("MST"));
	assertEquals("1984-03-22T07:32:01-07:00", DateTimeUtils.calendarToXSDDateTimeString(cal));
}
 
Example 25
Project: Mint-Programming-Language   File: AmPm.java View source code 6 votes vote down vote up
@Override
public Pointer apply(SmartList<Pointer> args) throws MintException {
    int amPm = new GregorianCalendar().get(Calendar.AM_PM);
    String _amPm;
    if (amPm == Calendar.AM)
        _amPm = "am";
    else
        _amPm = "pm";
    return Heap.allocateString(_amPm);
}
 
Example 26
Project: richfaces   File: CalendarRenderTest.java View source code 6 votes vote down vote up
@Test
public void testCalendarScrolling() throws Exception {
    HtmlPage page = environment.getPage("/calendarTest.jsf");

    HtmlImage calendarPopupButton = (HtmlImage) page.getElementById("form:calendarPopupButton");
    assertNotNull(calendarPopupButton);
    page = (HtmlPage) calendarPopupButton.click();
    HtmlElement calendarHeaderElement = page.getHtmlElementById("form:calendarHeader");
    assertNotNull("form:calendarHeader element missed.", calendarHeaderElement);

    HtmlTableDataCell nextTD = null;
    List<?> tds = calendarHeaderElement.getByXPath("table/tbody/tr/td");
    for (Object td : tds) {
        HtmlTableDataCell htdc = (HtmlTableDataCell) td;
        if (">".equals(htdc.asText())) {
            nextTD = htdc;
        }
    }
    assertNotNull(nextTD);
    HtmlElement div = (HtmlElement) nextTD.getChildElements().iterator().next();

    // Before click
    Calendar calendar = Calendar.getInstance();
    calendar.set(CalendarBean.CURRENT_YEAR, CalendarBean.CURRENT_MONTH, CalendarBean.CURRENT_DAY);
    String month = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
    assertTrue(calendarHeaderElement.asText().indexOf(month) > -1);

    page = div.click();

    // After click
    calendar.add(Calendar.MONTH, 1);
    month = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
    assertTrue(calendarHeaderElement.asText().indexOf(month) > -1);
}
 
Example 27
Project: openmuc   File: LoggerUtils.java View source code 6 votes vote down vote up
/**
 * Returns all filenames of the given timespan defined by the two dates
 * 
 * @param loggingInterval
 * @param startTimestamp
 * @param endTimestamp
 * @return a list of files which within the timespan
 */
public static List<String> getFilenames(int loggingInterval, int logTimeOffset, long startTimestamp,
		long endTimestamp) {

	Calendar calendarStart = new GregorianCalendar(Locale.getDefault());
	calendarStart.setTimeInMillis(startTimestamp);
	Calendar calendarEnd = new GregorianCalendar(Locale.getDefault());
	calendarEnd.setTimeInMillis(endTimestamp);

	// Rename timespanToFilenames....
	// Filename YYYYMMDD_<LoggingIntervall>.dat
	List<String> filenames = new ArrayList<String>();
	while (calendarStart.before(calendarEnd) || calendarStart.equals(calendarEnd)) {
		String filename = buildFilename(loggingInterval, logTimeOffset, calendarStart);
		filenames.add(filename);

		// set date to 00:00:00 of the next day
		calendarStart.add(Calendar.DAY_OF_MONTH, 1);
		calendarStart.set(Calendar.HOUR_OF_DAY, 0);
		calendarStart.set(Calendar.MINUTE, 0);
		calendarStart.set(Calendar.SECOND, 0);
		calendarStart.set(Calendar.MILLISECOND, 0);
	}
	return filenames;
}
 
Example 28
Project: JFugue-for-Android   File: ExsltDatetime.java View source code 6 votes vote down vote up
/**
 * The date:day-in-year function returns the day of a date in a year 
 * as a number. If no argument is given, then the current local
 * date/time, as returned by date:date-time is used the default argument.
 * The date/time string specified as the argument is a right-truncated 
 * string in the format defined as the lexical representation of xs:dateTime
 * in one of the formats defined in 
 * <a href="http://www.w3.org/TR/xmlschema-2/">[XML Schema Part 2: Datatypes]</a>. 
 * The permitted formats are as follows:
 *     xs:dateTime (CCYY-MM-DDThh:mm:ss)
 *     xs:date (CCYY-MM-DD) 
 * If the date/time string is not in one of these formats, then NaN is returned. 
 */
public static double dayInYear(String datetimeIn)
  throws ParseException
{
  String[] edz = getEraDatetimeZone(datetimeIn);
  String datetime = edz[1];
  if (datetime == null) 
    return Double.NaN;            
  
  String[] formats = {dt, d};
  return getNumber(datetime, formats, Calendar.DAY_OF_YEAR);
}
 
Example 29
Project: nmonvisualizer   File: IOStatPostParser.java View source code 6 votes vote down vote up
protected void addComponents(JPanel content, GridBagConstraints labelConstraints,
        GridBagConstraints fieldConstraints) {

    date = new JSpinner(new SpinnerDateModel(new Date(TimeHelper.today()), null, null, Calendar.DAY_OF_WEEK));
    date.setEditor(new DateEditor(date, "MMM dd yyyy"));

    JLabel dateLabel = new JLabel("Date:");
    dateLabel.setFont(Styles.LABEL);
    dateLabel.setHorizontalAlignment(SwingConstants.TRAILING);

    content.add(dateLabel, labelConstraints);
    content.add(date, fieldConstraints);
}
 
Example 30
Project: beepme   File: UptimeTable.java View source code 6 votes vote down vote up
public List<Uptime> getUptimesOfDay(Calendar day) {
	// all uptimes that BEGIN or END on that day
	if (day.isSet(Calendar.YEAR) && day.isSet(Calendar.MONTH) && day.isSet(Calendar.DAY_OF_MONTH)) {
		ArrayList<Uptime> list = new ArrayList<Uptime>();
		
		// get start and end timestamp of day
		long startOfDay = day.getTimeInMillis();
		day.roll(Calendar.DAY_OF_MONTH, true);
		long endOfDay = day.getTimeInMillis();
		day.roll(Calendar.DAY_OF_MONTH, false);
		
		SQLiteDatabase db = getDb();
		
		// distinct start values
		Cursor cursor = db.query(true, getTableName(), new String[] { "_id", "start", "end", "timerProfileId" },
				"start between ? and ? OR end between ? and ?", new String[] { String.valueOf(startOfDay),
				String.valueOf(endOfDay), String.valueOf(startOfDay),
				String.valueOf(endOfDay) }, "start", null, "start DESC", null);
		
		if (cursor != null && cursor.getCount() > 0) {
			cursor.moveToFirst();
			do {
				Uptime u = new Uptime(cursor.getLong(0));
				u.setStart(new Date(cursor.getLong(1)));
				if (!cursor.isNull(2)) {
					u.setEnd(new Date(cursor.getLong(2)));
				}
				u.setTimerProfileId(cursor.getInt(3));
				
				list.add(u);
			}
			while (cursor.moveToNext());
			cursor.close();
		}
		db.close();
		
		return list;
	}
	return null;
}
 
Example 31
Project: ijoomer-adv-sdk   File: IjoomerUtilities.java View source code 6 votes vote down vote up
/**
 * This method used to calculate times ago from milliseconds.
 * 
 * @param miliseconds
 *            represented [email protected] Long} milliseconds
 * @return represented [email protected] String}
 */
public static String calculateTimesAgo(long miliseconds) {
	Date start = new Date(miliseconds);
	Date end = new Date();

	long diffInSeconds = (end.getTime() - start.getTime()) / 1000;

	long diff[] = new long[] { 0, 0, 0, 0 };
	/* sec */diff[3] = (diffInSeconds >= 60 ? diffInSeconds % 60 : diffInSeconds);
	/* min */diff[2] = (diffInSeconds = (diffInSeconds / 60)) >= 60 ? diffInSeconds % 60 : diffInSeconds;
	/* hours */diff[1] = (diffInSeconds = (diffInSeconds / 60)) >= 24 ? diffInSeconds % 24 : diffInSeconds;
	/* days */diff[0] = (diffInSeconds = (diffInSeconds / 24));

	System.out.println(String.format("%d day%s, %d hour%s, %d minute%s, %d second%s ago", diff[0], diff[0] > 1 ? "s" : "", diff[1],
			diff[1] > 1 ? "s" : "", diff[2], diff[2] > 1 ? "s" : "", diff[3], diff[3] > 1 ? "s" : ""));

	if (diff[0] > 0) {
		Calendar c = Calendar.getInstance();
		c.setTime(start);

		if (c.getMaximum(Calendar.DATE) <= diff[0]) {
			return (String) DateFormat.format(IjoomerApplicationConfiguration.dateFormat, start);
		} else {
			return diff[0] > 1 ? String.format("%d days ago", diff[0]) : String.format("%d day ago", diff[0]);
		}
	} else if (diff[1] > 0) {
		return diff[1] > 1 ? String.format("%d hours ago", diff[1]) : String.format("%d hour ago", diff[1]);
	} else if (diff[2] > 0) {
		return diff[2] > 1 ? String.format("%d minutes ago", diff[2]) : String.format("%d minute ago", diff[2]);
	} else if (diff[3] > 0) {
		return diff[3] > 1 ? String.format("%d seconds ago", diff[3]) : String.format("%d second ago", diff[3]);
	} else {
		return (String) DateFormat.format(IjoomerApplicationConfiguration.dateFormat, start);
	}

}
 
Example 32
Project: ioke   File: DateTime.java View source code 6 votes vote down vote up
public DateTime cast (int newComponents)
{
  int oldComponents = mask & ~TIMEZONE_MASK;
  if (newComponents == oldComponents)
    return this;
  DateTime copy
    = new DateTime(newComponents, (GregorianCalendar) calendar.clone());
  if ((newComponents & ~oldComponents) != 0
      // Special case: Casting xs:date to xs:dateTime *is* allowed.
      && ! (oldComponents == DATE_MASK
            && newComponents == (DATE_MASK|TIME_MASK)))
    throw new ClassCastException("cannot cast DateTime - missing conponents");
  if (isZoneUnspecified())
    copy.mask &= ~TIMEZONE_MASK;
  else
    copy.mask |= TIMEZONE_MASK;
  int extraComponents = oldComponents & ~newComponents;
  if ((extraComponents & TIME_MASK) != 0)
    {
      copy.calendar.clear(Calendar.HOUR_OF_DAY);
      copy.calendar.clear(Calendar.MINUTE);
      copy.calendar.clear(Calendar.SECOND);
    }
  else
    copy.nanoSeconds = nanoSeconds;
  if ((extraComponents & YEAR_MASK) != 0)
    {
      copy.calendar.clear(Calendar.YEAR);
      copy.calendar.clear(Calendar.ERA);
    }
  if ((extraComponents & MONTH_MASK) != 0)
    copy.calendar.clear(Calendar.MONTH);
  if ((extraComponents & DAY_MASK) != 0)
    copy.calendar.clear(Calendar.DATE);
  return copy;
}
 
Example 33
Project: EclipseTrader   File: CDateTime.java View source code 6 votes vote down vote up
void fieldFirst() {
	if(Calendar.ZONE_OFFSET == getCalendarField(field[0])) {
		setActiveField(1);
	} else {
		setActiveField(0);
	}
}
 
Example 34
Project: resin   File: CalendarSerializer.java View source code 6 votes vote down vote up
/**
 * java.util.Calendar serializes to com.caucho.hessian.io.CalendarHandle
 */
@Override
public Object writeReplace(Object obj)
{
  Calendar cal = (Calendar) obj;

  return new CalendarHandle(cal.getClass(), cal.getTimeInMillis());
}
 
Example 35
Project: classpath   File: SpinnerDateModel.java View source code 6 votes vote down vote up
/**
 * Sets the date field to change when calculating the next and previous
 * values. It must be a valid [email protected] Calendar} field, excluding
 * [email protected] Calendar#ZONE_OFFSET} and [email protected] Calendar#DST_OFFSET}.
 *
 * @param calendarField  the calendar field to set.
 *
 * @throws IllegalArgumentException if <code>calendarField</code> is not
 *         a valid code.
 */
public void setCalendarField(int calendarField)
{
  if (calendarField < 0 || calendarField >= Calendar.FIELD_COUNT
      || calendarField == Calendar.ZONE_OFFSET
      || calendarField == Calendar.DST_OFFSET)
    throw new IllegalArgumentException("Illegal calendarField");

  if (this.calendarField != calendarField)
    {
      this.calendarField = calendarField;
      fireStateChanged();
    }
}
 
Example 36
Project: streamline   File: FastDateFormat.java View source code 6 votes vote down vote up
/**
 * [email protected]}
 */
public void appendTo(StringBuffer buffer, Calendar calendar) {
    int value = calendar.get(Calendar.HOUR);
    if (value == 0) {
        value = calendar.getLeastMaximum(Calendar.HOUR) + 1;
    }
    mRule.appendTo(buffer, value);
}
 
Example 37
Project: ProjectLibre   File: CalendarUtil.java View source code 6 votes vote down vote up
public static void weekFloor(Calendar calendar) {
	int i = calendar.get(Calendar.YEAR);
	int k = calendar.get(Calendar.DAY_OF_YEAR);
	int l = calendar.get(Calendar.DAY_OF_WEEK);
	int i1 = calendar.getFirstDayOfWeek();
	int j1 = l - i1;
	if(j1 > 0)
		k -= j1;
	else
	if(j1 < 0)
		k -= 7 + j1;
	calendar.clear();
	boolean flag = calendar.isLenient();
	if(!flag)
		calendar.setLenient(true);
	calendar.set(Calendar.YEAR, i);
	calendar.set(Calendar.DAY_OF_YEAR, k);
	if(!flag) {
		int j = calendar.get(Calendar.YEAR);
		calendar.setLenient(false);
	}
}
 
Example 38
Project: Calendar-Application   File: JLocaleChooser.java View source code 6 votes vote down vote up
/**
 * Default JLocaleChooser constructor.
 */
public JLocaleChooser(JComponent component) {
	super();
	this.component = component;
	addItemListener(this);
	locales = Calendar.getAvailableLocales();
	localeCount = locales.length;

	for (int i = 0; i < localeCount; i++) {
		if (locales[i].getCountry().length() > 0) {
			addItem(locales[i].getDisplayName());
		}
	}

	setLocale(Locale.getDefault());
}
 
Example 39
Project: jentrata-msh   File: InboundMessageProcessor.java View source code 5 votes vote down vote up
/**
 * Convert a string of data type "dateTime" as specified by XML-Schema Part
 * 2: Datatypes section 3.2.7 to local date/time. Only date/time represented
 * as CCYY-MM-DDThh:mm:ssZ is supported.
 * 
 * @param dateTime
 *            Date/time string in UTC.
 * 
 * @return local time representation of the given UTC time string.
 */
private Date fromUTCString(String dateTime) {
	try {
		ArrayList parts = new ArrayList();
		int i, j;
		for (i = 0, j = 0; i < dateTime.length(); i++) {
			if ("-+:TZ.".indexOf(dateTime.charAt(i)) != -1
					|| i == dateTime.length() - 1) {
				parts.add(dateTime.substring(j, i));
				j = i + 1;
			}
		}

		// Check if all date/time components exist or not
		int count = parts.size();
		if (count < 6)
			return null;

		int year = Integer.parseInt((String) parts.get(0));
		int month = Integer.parseInt((String) parts.get(1));
		int day = Integer.parseInt((String) parts.get(2));
		int hour = Integer.parseInt((String) parts.get(3));
		int minute = Integer.parseInt((String) parts.get(4));
		int second = Integer.parseInt((String) parts.get(5));

		if (count == 8) {
			int hourOffset = Integer.parseInt((String) parts.get(6));
			int minOffset = Integer.parseInt((String) parts.get(7));
			if (dateTime.indexOf("+") != -1) {
				hour -= hourOffset;
				minute -= minOffset;
			} else {
				hour += hourOffset;
				minute += minOffset;
			}
		}

		final Calendar c = Calendar
				.getInstance(TimeZone.getTimeZone("GMT"));
		c.clear();

		// In Calendar class, January = 0
		c.set(year, month - 1, day, hour, minute, second);
		return c.getTime();

	} catch (NumberFormatException nfe) {
		return null;
	}
}
 
Example 40
Project: jentrata-msh   File: EbmsUtility.java View source code 5 votes vote down vote up
/**
 * Convert an UTC representation of string <code>dateTime</code> to java calendar object. 
 * 
 * Followings are UTC conformed patterns:  
 * <ul>
 * <li>2007-07-16T13:24:56<li>
 * <li>2007-07-16T13:24:56Z<li>
 * <li>2007-07-16T13:24:56.789<li>
 * <li>2007-07-16T13:24:56.789Z<li>
 * <li>2007-07-16T13:24:56+02:00<li>
 * <li>2007-07-16T13:24:56-02:00<li>
 * <li>2007-07-16T13:24:56.789+02:00<li>
 * <li>2007-07-16T13:24:56.789-02:00<li>
 * </ul>
 * 
 * @param dateTime A string representing a UTC datetime. 
 * @return A java clendar object representing the <code>dateTime</code>
 * @throws UtilitiesException	When unable to convert the dateTime format.
 */
public static Calendar UTC2Calendar(String dateTime) throws UtilitiesException {
	Matcher m = UTC_PATTERNER.matcher(dateTime);

	if (m.matches() && m.groupCount() == UTC_CAPTURE_GROUP) {
		
		int[] parts = new int[UTC_CAPTURE_GROUP - 1];
		
		// parsing year, month, days, hours, minutes and second.
		int i;
		// i = 0 is group of whole pattern
		for (i = 0; i < 6; i++)
			parts[i] = Integer.parseInt(m.group(i + 1));
		
		// parsing millesecond (OPTIONAL)
		String ms = m.group(i + 1);
		if (ms == null) {
			parts[i++] = 0;
		} else {
			if (ms.length() > 3)
				ms = ms.substring(0, 3); // chop the sub second part to millesecond.
			parts[i++] = Integer.parseInt(ms);
		}
		
		// parsing Timezone (Z OR [+-]hh:mm)
		String tzStr = m.group(i + 1);
		TimeZone tz = null;
		
		if (tzStr == null || tzStr.equals("Z")) // Case with or without Z
			tz = TimeZone.getTimeZone("UTC");
		else
			tz = TimeZone.getTimeZone("GMT" + tzStr);

		
		Calendar c = Calendar.getInstance();
		c.clear();
		c.setTimeZone(tz);
		c.set(parts[0], parts[1]-1, parts[2], parts[3], parts[4], parts[5]);
		c.add(Calendar.MILLISECOND, parts[6]); // parts[6] = millescond
		return c; // parts[6] = millescond

	} else {
		throw new UtilitiesException("Unable to convert datetime to UTC format:" + dateTime);
	}						
}
 
Example 41
Project: richfaces   File: AbstractCalendar.java View source code 5 votes vote down vote up
public Date[] getPreloadDateRange() {
    FacesContext facesContext = FacesContext.getCurrentInstance();

    Date dateRangeBegin = null;
    Date dateRangeEnd = null;

    Mode mode = getMode();
    if (mode == null) {
        mode = Mode.client;
    }

    if (Mode.ajax.equals(mode)) {
        dateRangeBegin = CalendarHelper.getAsDate(facesContext, this,
                getDefaultPreloadBegin((Date) getCurrentDateOrDefault()));
        dateRangeEnd = CalendarHelper.getAsDate(facesContext, this, getDefaultPreloadEnd((Date) getCurrentDateOrDefault()));
    } else {

        Object date = getPreloadDateRangeBegin();
        if (date == null) {
            date = getDefaultPreloadBegin(getCurrentDateOrDefault());
        }
        dateRangeBegin = CalendarHelper.getAsDate(facesContext, this, date);

        date = getPreloadDateRangeEnd();
        if (date == null) {
            date = getDefaultPreloadEnd(getCurrentDateOrDefault());
        }
        dateRangeEnd = CalendarHelper.getAsDate(facesContext, this, date);
    }

    if (dateRangeBegin == null && dateRangeEnd == null) {
        return null;
    } else {
        if (dateRangeBegin.after(dateRangeEnd)) {
            // XXX add message
            FacesMessage message = new FacesMessage("preloadDateRangeBegin is greater than preloadDateRangeEnd");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            facesContext.addMessage(getClientId(facesContext), message);
            throw new IllegalArgumentException();
        }

        List<Date> dates = new ArrayList<Date>();

        Calendar calendar = Calendar.getInstance(CalendarHelper.getTimeZoneOrDefault(this),
                CalendarHelper.getAsLocale(facesContext, this, this.getLocale()));
        Calendar calendar2 = (Calendar) calendar.clone();
        calendar.setTime(dateRangeBegin);
        calendar2.setTime(dateRangeEnd);

        do {
            dates.add(calendar.getTime());
            calendar.add(Calendar.DATE, 1);
        } while (!calendar.after(calendar2));

        return (Date[]) dates.toArray(new Date[dates.size()]);
    }
}
 
Example 42
Project: my-ministry-assistant   File: MinistryDatabase.java View source code 5 votes vote down vote up
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.d(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion);

    /** NOTE: This switch statement is designed to handle cascading database updates, starting at the current version and falling through
     *  to all future upgrade cases. Only use "break;" when you want to drop and recreate the entire database.
     */
    int version = oldVersion;
    
    switch (version) {
        case VER_LAUNCH:
        	versionBackup(version);
            /** Version 2 added column for return visits. */
        	db.execSQL("ALTER TABLE " + Tables.TIMES + " ADD COLUMN returnVisits INTEGER DEFAULT 0");
            version = VER_ADD_RETURN_VISITS;
        case VER_ADD_RETURN_VISITS:
        	versionBackup(version);
        	db.execSQL("ALTER TABLE " + Tables.ENTRY_TYPES + " RENAME TO " + Tables.ENTRY_TYPES + "_tmp");
        	db.execSQL("ALTER TABLE " + Tables.HOUSEHOLDERS + " RENAME TO " + Tables.HOUSEHOLDERS + "_tmp");
        	db.execSQL("ALTER TABLE " + Tables.LITERATURE + " RENAME TO " + Tables.LITERATURE + "_tmp");
        	db.execSQL("ALTER TABLE " + Tables.PIONEERING + " RENAME TO " + Tables.PIONEERING + "_tmp");
        	db.execSQL("ALTER TABLE " + Tables.PLACED_LITERATURE + " RENAME TO " + Tables.PLACED_LITERATURE + "_tmp");
        	db.execSQL("ALTER TABLE " + Tables.PUBLISHERS + " RENAME TO " + Tables.PUBLISHERS + "_tmp");
        	db.execSQL("ALTER TABLE " + Tables.ROLLOVER + " RENAME TO " + Tables.ROLLOVER + "_tmp");
        	db.execSQL("ALTER TABLE " + Tables.TIMES + " RENAME TO " + Tables.TIMES + "_tmp");
        	db.execSQL("ALTER TABLE " + Tables.TYPES_OF_LIERATURE + " RENAME TO " + Tables.TYPES_OF_LIERATURE + "_tmp");
        	
        	db.execSQL("DROP TABLE IF EXISTS " + Tables.ENTRY_TYPES);
            db.execSQL("DROP TABLE IF EXISTS " + Tables.HOUSEHOLDERS);
            db.execSQL("DROP TABLE IF EXISTS " + Tables.LITERATURE);
            db.execSQL("DROP TABLE IF EXISTS " + Tables.PLACED_LITERATURE);
            db.execSQL("DROP TABLE IF EXISTS " + Tables.PUBLISHERS);
            db.execSQL("DROP TABLE IF EXISTS " + Tables.ROLLOVER);
            db.execSQL("DROP TABLE IF EXISTS " + Tables.TIMES);
            db.execSQL("DROP TABLE IF EXISTS " + Tables.TYPES_OF_LIERATURE);
            db.execSQL("DROP TABLE IF EXISTS " + Tables.PIONEERING);
            
            onCreate(db);
            
            /** Hack to get around not creating the defaults so there aren't any records in the table */
            db.execSQL("DROP TABLE IF EXISTS " + Tables.ENTRY_TYPES);
            db.execSQL(EntryType.SCRIPT_CREATE);
            db.execSQL("DROP TABLE IF EXISTS " + Tables.TYPES_OF_LIERATURE);
            db.execSQL(LiteratureType.SCRIPT_CREATE);
            /** End Hack */
            
            updateEntryTypes(db);
            updateHouseholders(db);
            updateLiterature(db);
            updateLiteratureTypes(db);
            updateLiteraturePlaced(db);
            updatePublishers(db);
            updateTime(db);
            updateRollover(db);
            
            db.execSQL("DROP TABLE IF EXISTS " + Tables.ENTRY_TYPES + "_tmp");
            db.execSQL("DROP TABLE IF EXISTS " + Tables.HOUSEHOLDERS + "_tmp");
            db.execSQL("DROP TABLE IF EXISTS " + Tables.LITERATURE + "_tmp");
            db.execSQL("DROP TABLE IF EXISTS " + Tables.TYPES_OF_LIERATURE + "_tmp");
            db.execSQL("DROP TABLE IF EXISTS " + Tables.PLACED_LITERATURE + "_tmp");
            db.execSQL("DROP TABLE IF EXISTS " + Tables.PUBLISHERS + "_tmp");
            db.execSQL("DROP TABLE IF EXISTS " + Tables.ROLLOVER + "_tmp");
            db.execSQL("DROP TABLE IF EXISTS " + Tables.TIMES + "_tmp");
            db.execSQL("DROP TABLE IF EXISTS " + Tables.PIONEERING + "_tmp");
            
            version = VER_DB_RESTRUCTURE;
        case VER_DB_RESTRUCTURE:
        	versionBackup(version);
        	db.execSQL("DROP TABLE IF EXISTS " + Tables.NOTES);
        	db.execSQL(Notes.SCRIPT_CREATE);
            version = VER_ADD_NOTES;
        case VER_ADD_NOTES:
        	versionBackup(version);
        	db.execSQL("ALTER TABLE " + Tables.TIMES + " RENAME TO " + Tables.TIMES + "_tmp");
        	db.execSQL(Time.SCRIPT_CREATE);
        	updateTimeV2(db);
        	db.execSQL("DROP TABLE IF EXISTS " + Tables.TIMES + "_tmp");
        	
            version = VER_ADD_END_DATE;
        case VER_ADD_END_DATE:
        	versionBackup(version);
        	db.execSQL("DROP TABLE IF EXISTS " + Tables.PIONEERING);
            version = VER_REMOVE_PIONEERING_TABLE;
        case VER_REMOVE_PIONEERING_TABLE:
        	versionBackup(version);
        	Cursor cursor = db.rawQuery("SELECT * FROM " + Tables.TYPES_OF_LIERATURE + " WHERE " + LiteratureType._ID + " = " + ID_TRACTS, null);
        	ContentValues values = new ContentValues();
        	
        	if(cursor.moveToFirst()) {
            	values.put(LiteratureType.NAME, cursor.getString(cursor.getColumnIndex(LiteratureType.NAME)));
            	values.put(LiteratureType.ACTIVE, cursor.getInt(cursor.getColumnIndex(LiteratureType.ACTIVE)));
            	values.put(LiteratureType.SORT_ORDER, cursor.getInt(cursor.getColumnIndex(LiteratureType.SORT_ORDER)));

        		ContentValues updatevalues = new ContentValues();
        		updatevalues.put(Literature.TYPE_OF_LIERATURE_ID, db.insert(Tables.TYPES_OF_LIERATURE, null, values));
        		db.update(Tables.LITERATURE, updatevalues, Literature.TYPE_OF_LIERATURE_ID + "=" + ID_TRACTS, null);

            	values.put(LiteratureType.NAME, mContext.getResources().getString(R.string.default_tracts));
            	values.put(LiteratureType.ACTIVE, MinistryService.ACTIVE);
            	values.put(LiteratureType.SORT_ORDER, ID_TRACTS);
            	
            	db.update(Tables.TYPES_OF_LIERATURE, values, BaseColumns._ID + "=" + ID_TRACTS, null);
        	}
        	else {
            	values.put(LiteratureType._ID, MinistryDatabase.ID_TRACTS);
            	values.put(LiteratureType.NAME, mContext.getResources().getString(R.string.default_tracts));
            	values.put(LiteratureType.ACTIVE, MinistryService.ACTIVE);
            	values.put(LiteratureType.SORT_ORDER, ID_TRACTS);
            	
            	db.insert(Tables.TYPES_OF_LIERATURE, null, values);
        	}
        	cursor.close();
        	
        	version = VER_ADD_TRACTS;
        case VER_ADD_TRACTS:
        	versionBackup(version);
        	MinistryService database = new MinistryService(mContext);
        	//SimpleDateFormat dbDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        	Calendar start = Calendar.getInstance(Locale.getDefault());
        	Calendar now = Calendar.getInstance(Locale.getDefault());
        	int minutes = 0;
        	int pubID = 0;
        	boolean found = false;
        	values = new ContentValues();
        	values.put(Rollover.PUBLISHER_ID, 0);
        	
        	/** Loop over each publisher for each available month to convert */
        	Cursor pubs = database.fetchAllPublishers(db);
        	Cursor theDate, ro;
        	
        	for(pubs.moveToFirst();!pubs.isAfterLast();pubs.moveToNext()) {
        		found = false;
        		pubID = pubs.getInt(pubs.getColumnIndex(Publisher._ID));
        		values.put(Rollover.PUBLISHER_ID, pubID);
        		
        		/** Get first RO date for publisher */
        		theDate = db.query(Tables.ROLLOVER, new String[] {Rollover._ID,Rollover.DATE}, Rollover.PUBLISHER_ID + " = " + pubID, null, null, null, Rollover.DATE, "1");
    			
    			if(theDate.moveToFirst()) {
    				found = true;
		try {
			start.setTime(TimeUtils.dbDateFormat.parse(theDate.getString(theDate.getColumnIndex(Rollover.DATE))));
		} catch (ParseException e) {
			start = Calendar.getInstance(Locale.getDefault());
		}
    			}
    			theDate.close();
    			
    			if(found) {
    				do {
          		minutes += Integer.valueOf(Helper.getMinuteDuration(database.fetchListOfHoursForMonthForPublisher(db, TimeUtils.dbDateFormat.format(start.getTime()), pubID)));
          		
          		if(minutes >= 60)
          			minutes -= 60;
          		
              	values.put(Rollover.DATE, TimeUtils.dbDateFormat.format(start.getTime()));
              	values.put(Rollover.MINUTES, minutes);
          		
          		/** Save the minutes back to the RO table */
          		ro = database.fetchRolloverRecord(db, pubID, TimeUtils.dbDateFormat.format(start.getTime()));
          		if(ro.moveToFirst())
          			database.saveRolloverMinutes(db, ro.getInt(ro.getColumnIndex(Rollover._ID)), values);
          		else
          			database.createRolloverMinutes(db, values);
          		ro.close();
          		start.add(Calendar.MONTH, 1);
    				} while(start.before(now));
    			}
        	}
        	
        	pubs.close();
        	
        	version = VER_CONVERT_ROLLOVER_TO_MINUTES;
        case VER_CONVERT_ROLLOVER_TO_MINUTES:
        	versionBackup(version);
        	db.execSQL("ALTER TABLE " + Tables.TIMES + " RENAME TO " + Tables.TIMES + "_tmp");
        	db.execSQL(Time.SCRIPT_CREATE);
        	updateTimeV3(db);
        	db.execSQL("DROP TABLE IF EXISTS " + Tables.TIMES + "_tmp");
        	
        	version = VER_REMOVE_TOTAL_TIME_COLUMN;
        case VER_REMOVE_TOTAL_TIME_COLUMN:
        	versionBackup(version);
        	db.execSQL("DROP TABLE IF EXISTS " + Tables.TYPES_OF_PIONEERING);
        	db.execSQL("DROP TABLE IF EXISTS " + Tables.PIONEERING);
        	
        	db.execSQL(PioneeringType.SCRIPT_CREATE);
        	db.execSQL(Pioneering.SCRIPT_CREATE);
        	createPioneeringTypeDefaults(db);
        	
        	version = VER_ADD_PIONEERING;
        case VER_ADD_PIONEERING:
        	versionBackup(version);
        	boolean shouldAlterTable = true;
        	Cursor checkCols = db.rawQuery("PRAGMA table_info(" + Tables.TIME_HOUSEHOLDERS + ")", null);
        	for(checkCols.moveToFirst();!checkCols.isAfterLast();checkCols.moveToNext()) {
        		if(checkCols.getString(checkCols.getColumnIndex("name")).equals(TimeHouseholder.RETURN_VISIT)) {
        			shouldAlterTable = false;
        			break;
        		}
        	}
        	checkCols.close();
        	
        	if(shouldAlterTable)
        		db.execSQL("ALTER TABLE " + Tables.TIME_HOUSEHOLDERS + " ADD COLUMN " + TimeHouseholder.RETURN_VISIT + " INTEGER DEFAULT 1");
        	
        	version = VER_ADD_IS_RETURN_VISIT;
        case VER_ADD_IS_RETURN_VISIT:
        	versionBackup(version);
        	
        	db.execSQL("ALTER TABLE " + Tables.HOUSEHOLDERS + " ADD COLUMN " + Householder.SORT_ORDER + " INTEGER DEFAULT 1");
        	
        	version = VER_ADD_HOUSEHOLDER_SORT_ORDER;
    }
}
 
Example 43
Project: aipo   File: ScheduleUtils.java View source code 5 votes vote down vote up
/**
 * ????????????????????????????
 *
 * @param date
 * @param ptn
 * @param startDate
 * @param limitDate
 * @return
 */
public static boolean isView(ALDateTimeField date, String ptn,
    Date startDate, Date limitDate) {
  int count = 0;
  boolean result = false;
  Calendar cal = Calendar.getInstance();
  cal.setTime(date.getValue());
  // ??
  if (ptn.charAt(0) == 'D') {
    result = true;
    count = 1;
    // ??, ???
  } else if (ptn.charAt(0) == 'W') {

    int dow = cal.get(Calendar.DAY_OF_WEEK);
    // ?????????????
    int dowim = cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);
    if (ptn.charAt(8) == 'N'
      || ptn.charAt(8) == 'L'
      || dowim == Character.getNumericValue(ptn.charAt(8))) {
      switch (dow) {
      // ?
        case Calendar.SUNDAY:
          result = ptn.charAt(1) != '0';
          break;
        // ?
        case Calendar.MONDAY:
          result = ptn.charAt(2) != '0';
          break;
        // ?
        case Calendar.TUESDAY:
          result = ptn.charAt(3) != '0';
          break;
        // ?
        case Calendar.WEDNESDAY:
          result = ptn.charAt(4) != '0';
          break;
        // ?
        case Calendar.THURSDAY:
          result = ptn.charAt(5) != '0';
          break;
        // ?
        case Calendar.FRIDAY:
          result = ptn.charAt(6) != '0';
          break;
        // ?
        case Calendar.SATURDAY:
          result = ptn.charAt(7) != '0';
          break;
        default:
          result = false;
          break;
      }
      if (ptn.length() == 9) {
        count = 8;
      } else {
        count = 9;
      }
    }
    // ??
  } else if (ptn.charAt(0) == 'M') {
    int mday = Integer.parseInt(ptn.substring(1, 3));
    result = Integer.parseInt(date.getDay()) == mday;
    count = 3;
  } else if (ptn.charAt(0) == 'Y') {
    int ymonth = Integer.parseInt(ptn.substring(1, 3));
    int yday = Integer.parseInt(ptn.substring(3, 5));
    int month = Integer.parseInt(date.getMonth());
    int day = Integer.parseInt(date.getDay());
    if (ymonth == month && yday == day) {
      result = true;
      count = 5;
    } else {
      result = false;
    }
  } else {
    return true;
  }

  if (result) {
    if (ptn.charAt(count) == 'L') {
      // ??????????
      if (equalsToDate(startDate, date.getValue(), false)
        || equalsToDate(limitDate, date.getValue(), false)) {
        // ????????????
        result = true;
      } else {
        // ???????????????????????????????
        result =
          result
            && startDate.before(cal.getTime())
            && limitDate.after(cal.getTime());
      }
    }
  }

  return result;
}
 
Example 44
Project: richfaces   File: CalendarRendererBase.java View source code 5 votes vote down vote up
protected Map<String, Object> getLocaleOptions(FacesContext facesContext, UIComponent component) {
    AbstractCalendar calendarComponent = (AbstractCalendar) component;

    Map<String, Object> map = new HashMap<String, Object>();

    Locale locale = CalendarHelper.getAsLocale(facesContext, calendarComponent);
    DateFormatSymbols dateFormat = new DateFormatSymbols(locale);

    Calendar calendar = CalendarHelper.getCalendar(facesContext, calendarComponent);
    int maximum = calendar.getActualMaximum(Calendar.DAY_OF_WEEK);
    int minimum = calendar.getActualMinimum(Calendar.DAY_OF_WEEK);

    int monthMax = calendar.getActualMaximum(Calendar.MONTH);
    int monthMin = calendar.getActualMinimum(Calendar.MONTH);

    String[] weekDayLabelsShort = RenderKitUtils.asArray(calendarComponent.getWeekDayLabelsShort());
    if (isEmptyArray(weekDayLabelsShort)) {
        weekDayLabelsShort = dateFormat.getShortWeekdays();
        weekDayLabelsShort = shiftDates(minimum, maximum, weekDayLabelsShort);
    }
    RenderKitUtils.addToScriptHash(map, WEEK_DAY_LABELS_SHORT, weekDayLabelsShort);

    String[] monthLabels = RenderKitUtils.asArray(calendarComponent.getMonthLabels());
    if (isEmptyArray(monthLabels)) {
        monthLabels = dateFormat.getMonths();
        monthLabels = shiftDates(monthMin, monthMax, monthLabels);
    }
    RenderKitUtils.addToScriptHash(map, MONTH_LABELS, monthLabels);

    String[] monthLabelsShort = RenderKitUtils.asArray(calendarComponent.getMonthLabelsShort());
    if (isEmptyArray(monthLabelsShort)) {
        monthLabelsShort = dateFormat.getShortMonths();
        monthLabelsShort = shiftDates(monthMin, monthMax, monthLabelsShort);
    }
    RenderKitUtils.addToScriptHash(map, MONTH_LABELS_SHORT, monthLabelsShort);

    int minDaysInFirstWeek = calendarComponent.getMinDaysInFirstWeek();

    if (1 > minDaysInFirstWeek || minDaysInFirstWeek > 7) {
        minDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek();
    }

    if (0 <= minDaysInFirstWeek && minDaysInFirstWeek <= 7) {
        RenderKitUtils.addToScriptHash(map, MIN_DAYS_IN_FIRST_WEEK, minDaysInFirstWeek);
    }

    int day = calendarComponent.getFirstWeekDay();
    if (day < 0 || 6 < day) {
        day = calendar.getFirstDayOfWeek() - calendar.getActualMinimum(Calendar.DAY_OF_WEEK);
    }

    if (0 <= day && day <= 6) {
        RenderKitUtils.addToScriptHash(map, FIRST_DAY_WEEK, day);
    } else {
        throw new IllegalArgumentException(day + " value of firstWeekDay attribute is not a legal one for component: "
            + MessageUtil.getLabel(facesContext, calendarComponent));
    }
    return map;
}
 
Example 45
Project: Android-Json-Parsing-Code-Sample   File: TimePickerDialog.java View source code 5 votes vote down vote up
public void applyStyle(int resId){
    mTimePicker.applyStyle(resId);

    Context context = getContext();
    mCheckBoxSize = ThemeUtil.dpToPx(context, 48);

    TypedArray a = context.obtainStyledAttributes(resId, R.styleable.TimePickerDialog);
    mHeaderHeight = a.getDimensionPixelSize(R.styleable.TimePickerDialog_tp_headerHeight, ThemeUtil.dpToPx(context, 120));
    mTextTimeColor = a.getColor(R.styleable.TimePickerDialog_tp_textTimeColor, 0xFF000000);
    mTextTimeSize = a.getDimensionPixelSize(R.styleable.TimePickerDialog_tp_textTimeSize, context.getResources().getDimensionPixelOffset(R.dimen.abc_text_size_headline_material));
    mIsLeadingZero = a.getBoolean(R.styleable.TimePickerDialog_tp_leadingZero, false);
    String am = a.getString(R.styleable.TimePickerDialog_tp_am);
    String pm = a.getString(R.styleable.TimePickerDialog_tp_pm);
    a.recycle();

    if(am == null)
        am = DateUtils.getAMPMString(Calendar.AM).toUpperCase();

    if(pm == null)
        pm = DateUtils.getAMPMString(Calendar.PM).toUpperCase();

    int[][] states = new int[][]{
            new int[]{-android.R.attr.state_checked},
            new int[]{android.R.attr.state_checked},
    };
    int[] colors = new int[]{
            mTimePicker.getTextColor(),
            mTimePicker.getTextHighlightColor(),
    };
    mAmView.setBackgroundColor(mTimePicker.getSelectionColor());
    mAmView.setAnimDuration(mTimePicker.getAnimDuration());
    mAmView.setInterpolator(mTimePicker.getInInterpolator(), mTimePicker.getOutInterpolator());
    mAmView.setTypeface(mTimePicker.getTypeface());
    mAmView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTimePicker.getTextSize());
    mAmView.setTextColor(new ColorStateList(states, colors));
    mAmView.setText(am);

    mPmView.setBackgroundColor(mTimePicker.getSelectionColor());
    mPmView.setAnimDuration(mTimePicker.getAnimDuration());
    mPmView.setInterpolator(mTimePicker.getInInterpolator(), mTimePicker.getOutInterpolator());
    mPmView.setTypeface(mTimePicker.getTypeface());
    mPmView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTimePicker.getTextSize());
    mPmView.setTextColor(new ColorStateList(states, colors));
    mPmView.setText(pm);

    mPaint.setTypeface(mTimePicker.getTypeface());

    mHour = String.format(mIsLeadingZero ? FORMAT : FORMAT_NO_LEADING_ZERO, !mTimePicker.is24Hour() && mTimePicker.getHour() == 0 ? 12 : mTimePicker.getHour());
    mMinute = String.format(FORMAT, mTimePicker.getMinute());

    if(!mTimePicker.is24Hour())
        mMidday = mIsAm ? mAmView.getText().toString() : mPmView.getText().toString();

    mLocationDirty = true;
    invalidate(0, 0, mHeaderRealWidth, mHeaderRealHeight);
}
 
Example 46
Project: plugins-cn   File: AdminPortlet.java View source code 5 votes vote down vote up
public void updateInterview(
		ActionRequest actionRequest, ActionResponse actionResponse)
	throws Exception {

	String currentURL = ParamUtil.getString(actionRequest, "currentURL");

	long interviewId = ParamUtil.getLong(actionRequest, "interviewId");
	long questionSetId = ParamUtil.getLong(actionRequest, "questionSetId");
	String name = ParamUtil.getString(actionRequest, "name");
	String emailAddress = ParamUtil.getString(
		actionRequest, "emailAddress");

	int expireDateYear = ParamUtil.getInteger(
		actionRequest, "expireDateYear");
	int expireDateMonth = ParamUtil.getInteger(
		actionRequest, "expireDateMonth");
	int expireDateDay = ParamUtil.getInteger(
		actionRequest, "expireDateDay");
	int expireDateHour = ParamUtil.getInteger(
		actionRequest, "expireDateHour");
	int expireDateMinute = ParamUtil.getInteger(
		actionRequest, "expireDateMinute");
	int expireDateAmPm = ParamUtil.getInteger(
		actionRequest, "expireDateAmPm");

	if (expireDateAmPm == Calendar.PM) {
		expireDateHour += 12;
	}

	ServiceContext serviceContext = ServiceContextFactory.getInstance(
		actionRequest);

	try {
		Interview interview = null;

		if (interviewId <= 0) {
			interview = InterviewLocalServiceUtil.addInterview(
				name, emailAddress, questionSetId, expireDateMonth,
				expireDateDay, expireDateYear, expireDateHour,
				expireDateMinute, serviceContext);
		}
		else {
			interview = InterviewLocalServiceUtil.updateInterview(
				interviewId, name, emailAddress, questionSetId,
				expireDateMonth, expireDateDay, expireDateYear,
				expireDateHour, expireDateMinute, serviceContext);
		}

		currentURL = HttpUtil.setParameter(
			currentURL, actionResponse.getNamespace() + "interviewId",
			interview.getInterviewId());
	}
	catch (Exception e) {
		if (e instanceof InterviewEmailAddressException ||
			e instanceof InterviewNameException) {

			SessionErrors.add(actionRequest, e.getClass().getName());

			actionResponse.setRenderParameter(
				"mvcPath", "/admin/edit_interview.jsp");
			actionResponse.setRenderParameter("redirect", currentURL);

			return;
		}
		else {
			throw e;
		}
	}

	actionRequest.setAttribute(WebKeys.REDIRECT, currentURL);

	sendRedirect(actionRequest, actionResponse);
}
 
Example 47
Project: EclipseTrader   File: CDateTime.java View source code 5 votes vote down vote up
/**
 * Set the style of this CDateTime to work with dates and / or times 
 * as determined by the given pattern. This will set the fields shown in the
 * text box and, if <code>DROP_DOWN</code> style is set, the fields of the
 * drop down component.<br>
 * This method is backed by an implementation of SimpleDateFormat, and as such,
 * any string pattern which is valid for SimpleDateFormat may be used.
 * Examples (US Locale):<br>
 * </code>setPattern("MM/dd/yyyy h:mm a");</code><br />
 * </code>setPattern("'Meeting @' h:mm a 'on' EEEE, MMM dd, yyyy");</code><br />
 * @param pattern the pattern to use, if it is invalid, the original is restored
 * @throws IllegalArgumentException
 * @see SimpleDateFormat
 * @see #getPattern()
 * @see #setFormat(int)
 */
public void setPattern(String pattern) throws IllegalArgumentException {
	if(isOpen()) {
		setOpen(false);
	}
	df = new SimpleDateFormat(pattern, locale);
	df.setTimeZone(timezone);
	if(updateFields()) {
		this.pattern = pattern;
		this.format = -1;
		boolean wasDate = isDate;
		boolean wasTime = isTime;
		isDate = isTime = false;
		calendarFields = new int[field.length];
		for(int i = 0; i < calendarFields.length; i++) {
			calendarFields[i] = getCalendarField(field[i]);
			switch(calendarFields[i]) {
			case Calendar.AM_PM:
			case Calendar.HOUR:
			case Calendar.HOUR_OF_DAY:
			case Calendar.MILLISECOND:
			case Calendar.MINUTE:
			case Calendar.SECOND:
				isTime = true;
				break;
			case Calendar.DAY_OF_MONTH:
			case Calendar.DAY_OF_WEEK:
			case Calendar.DAY_OF_WEEK_IN_MONTH:
			case Calendar.DAY_OF_YEAR:
			case Calendar.ERA:
			case Calendar.MONTH:
			case Calendar.WEEK_OF_MONTH:
			case Calendar.WEEK_OF_YEAR:
			case Calendar.YEAR:
				isDate = true;
				break;
			default:
				break;
			}
		}
		if(checkButton() && ((isDate != wasDate) || (isTime != wasTime))) {
			if(defaultButtonImage) {
				if(isDate) {
					doSetButtonImage(Resources.getIconCalendar());
				} else {
					doSetButtonImage(Resources.getIconClock());
				}
			}
			updateNullText();
		}
		if(checkText()) {
			updateText();
		}
		if(isSimple()) {
			disposePicker();
			createPicker();
		}
	} else {
		throw new IllegalArgumentException("Problem setting pattern: \"" + pattern + "\""); //$NON-NLS-1$ //$NON-NLS-2$
	}
}
 
Example 48
Project: property-db   File: SimpleDateFormat.java View source code 5 votes vote down vote up
/** [email protected]} 
 * Private member function that does the real date/time formatting.
 */
private void subFormat(int patternCharIndex, int count,
                       FieldDelegate delegate, StringBuffer buffer,
                       boolean useDateFormatSymbols)
{
    int     maxIntCount = Integer.MAX_VALUE;
    String  current = null;
    int     beginOffset = buffer.length();

    int field = PATTERN_INDEX_TO_CALENDAR_FIELD[patternCharIndex];
    int value = calendar.get(field);
    int style = (count >= 4) ? Calendar.LONG : Calendar.SHORT;
    if (!useDateFormatSymbols) {
        current = calendar.getDisplayName(field, style, locale);
    }

    // Note: zeroPaddingNumber() assumes that maxDigits is either
    // 2 or maxIntCount. If we make any changes to this,
    // zeroPaddingNumber() must be fixed.

    switch (patternCharIndex) {
    case 0: // 'G' - ERA
        if (useDateFormatSymbols) {
            String[] eras = formatData.getEras();
            if (value < eras.length)
                current = eras[value];
        }
        if (current == null)
            current = "";
        break;

    case 1: // 'y' - YEAR
        if (calendar instanceof GregorianCalendar) {
            if (count >= 4)
                zeroPaddingNumber(value, count, maxIntCount, buffer);
            else // count < 4
                zeroPaddingNumber(value, 2, 2, buffer); // clip 1996 to 96
        } else {
            if (current == null) {
                zeroPaddingNumber(value, style == Calendar.LONG ? 1 : count,
                                  maxIntCount, buffer);
            }
        }
        break;

    case 2: // 'M' - MONTH
        if (useDateFormatSymbols) {
            String[] months;
            if (count >= 4) {
                months = formatData.getMonths();
                current = months[value];
            } else if (count == 3) {
                months = formatData.getShortMonths();
                current = months[value];
            }
        } else {
            if (count < 3) {
                current = null;
            }
        }
        if (current == null) {
            zeroPaddingNumber(value+1, count, maxIntCount, buffer);
        }
        break;

    case 4: // 'k' - HOUR_OF_DAY: 1-based.  eg, 23:59 + 1 hour =>> 24:59
        if (current == null) {
            if (value == 0)
                zeroPaddingNumber(calendar.getMaximum(Calendar.HOUR_OF_DAY)+1,
                                  count, maxIntCount, buffer);
            else
                zeroPaddingNumber(value, count, maxIntCount, buffer);
        }
        break;

    case 9: // 'E' - DAY_OF_WEEK
        if (useDateFormatSymbols) {
            String[] weekdays;
            if (count >= 4) {
                weekdays = formatData.getWeekdays();
                current = weekdays[value];
            } else { // count < 4, use abbreviated form if exists
                weekdays = formatData.getShortWeekdays();
                current = weekdays[value];
            }
        }
        break;

    case 14:    // 'a' - AM_PM
        if (useDateFormatSymbols) {
            String[] ampm = formatData.getAmPmStrings();
            current = ampm[value];
        }
        break;

    case 15: // 'h' - HOUR:1-based.  eg, 11PM + 1 hour =>> 12 AM
        if (current == null) {
            if (value == 0)
                zeroPaddingNumber(calendar.getLeastMaximum(Calendar.HOUR)+1,
                                  count, maxIntCount, buffer);
            else
                zeroPaddingNumber(value, count, maxIntCount, buffer);
        }
        break;

    case 17: // 'z' - ZONE_OFFSET
        if (current == null) {
            if (formatData.locale == null || formatData.isZoneStringsSet) {
                int zoneIndex =
                    formatData.getZoneIndex(calendar.getTimeZone().getID());
                if (zoneIndex == -1) {
                    value = calendar.get(Calendar.ZONE_OFFSET) +
                        calendar.get(Calendar.DST_OFFSET);
                    buffer.append(ZoneInfoFile.toCustomID(value));
                } else {
                    int index = (calendar.get(Calendar.DST_OFFSET) == 0) ? 1: 3;
                    if (count < 4) {
                        // Use the short name
                        index++;
                    }
                    String[][] zoneStrings = formatData.getZoneStringsWrapper();
                    buffer.append(zoneStrings[zoneIndex][index]);
                }
            } else {
                TimeZone tz = calendar.getTimeZone();
                boolean daylight = (calendar.get(Calendar.DST_OFFSET) != 0);
                int tzstyle = (count < 4 ? TimeZone.SHORT : TimeZone.LONG);
                buffer.append(tz.getDisplayName(daylight, tzstyle, formatData.locale));
            }
        }
        break;

    case 18: // 'Z' - ZONE_OFFSET ("-/+hhmm" form)
        value = (calendar.get(Calendar.ZONE_OFFSET) +
                 calendar.get(Calendar.DST_OFFSET)) / 60000;

        int width = 4;
        if (value >= 0) {
            buffer.append('+');
        } else {
            width++;
        }

        int num = (value / 60) * 100 + (value % 60);
        CalendarUtils.sprintf0d(buffer, num, width);
        break;

    default:
        // case 3: // 'd' - DATE
        // case 5: // 'H' - HOUR_OF_DAY:0-based.  eg, 23:59 + 1 hour =>> 00:59
        // case 6: // 'm' - MINUTE
        // case 7: // 's' - SECOND
        // case 8: // 'S' - MILLISECOND
        // case 10: // 'D' - DAY_OF_YEAR
        // case 11: // 'F' - DAY_OF_WEEK_IN_MONTH
        // case 12: // 'w' - WEEK_OF_YEAR
        // case 13: // 'W' - WEEK_OF_MONTH
        // case 16: // 'K' - HOUR: 0-based.  eg, 11PM + 1 hour =>> 0 AM
        if (current == null) {
            zeroPaddingNumber(value, count, maxIntCount, buffer);
        }
        break;
    } // switch (patternCharIndex)

    if (current != null) {
        buffer.append(current);
    }

    int fieldID = PATTERN_INDEX_TO_DATE_FORMAT_FIELD[patternCharIndex];
    Field f = PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID[patternCharIndex];

    delegate.formatted(fieldID, f, f, beginOffset, buffer.length(), buffer);
}