Example usage for java.util Calendar HOUR

List of usage examples for java.util Calendar HOUR

Introduction

In this page you can find the example usage for java.util Calendar HOUR.

Prototype

int HOUR

To view the source code for java.util Calendar HOUR.

Click Source Link

Document

Field number for get and set indicating the hour of the morning or afternoon.

Usage

From source file:com.jdom.junit.utils.AbstractFixture.java

/**
 * Get a randomized value./*from ww w  .  j av a  2  s  . c  om*/
 * 
 * @param value
 *            the value to randomize
 * @param salt
 *            the randomizer to use
 * @return the randomized value
 */
public static Date getSaltedValue(Date value, int salt) {
    Date retValue;

    if (salt == 0) {
        retValue = value;
    } else {
        Calendar cal = Calendar.getInstance();
        cal.setTime(value);
        cal.add(Calendar.HOUR, salt);
        retValue = cal.getTime();
    }

    return retValue;
}

From source file:amhamogus.com.daysoff.fragments.AddEventFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_add_event, container, false);
    ButterKnife.bind(this, rootView);

    getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    addEventHeader.setText(calendarId);/*from w ww .  j av  a2 s.  c  o m*/

    // Set default date and time values
    // based on the current time
    final Calendar currentDate = Calendar.getInstance();
    hour = currentDate.get(Calendar.HOUR);
    minute = currentDate.get(Calendar.MINUTE);
    amOrPm = currentDate.get(Calendar.AM_PM);

    if (amOrPm == Calendar.AM) {
        noonOrNight = "AM";
    } else {
        noonOrNight = "PM";
    }

    // By default, events are set to 30 minutes. Based on the
    // current minute value round to the next 30 minute set
    if (minute <= 29) {
        // Minute value is between 0 and 29.
        // Set the start time to half past.
        minute = 30;
        // Set end time to the the next hour.
        futureMinute = 0;
        // Set future hour to the next hour.
        if (hour > 12) {
            // The app tries to mange hours in 12 hour format
            // So hour values should not exceed 12. If hour does
            // exceed 12, we convert to 12 hour format.
            hour = hour - 12;
            futureHour = hour + 1;
        } else if (hour == 0) {
            // In 12 hour format. Convert 0 to 12.
            // Noon or midnight is set to '0' which is not
            // helpful for users, thus we change 0 to 12
            hour = 12;
            futureHour = 1;
        } else {
            //
            futureHour = hour + 1;
        }
    } else {
        // Current minute is between 30 and 60.
        // Round to the nearest hour.
        minute = 0;
        futureMinute = 30;

        if (hour > 12) {
            // The app tries to mange hours in 12 hour format
            // So hour values should not exceed 12. If hour does
            // exceed 12, we convert to 12 hour format.
            hour = hour - 12;
            futureHour = hour;
        } else if (hour == 0 || hour == 12) {
            // In 12 hour format. Convert 0 to 12.
            // Noon or midnight is set to '0' which is not
            // helpful for users, thus we change 0 to 12
            hour = 1;
            futureHour = 1;
        } else {
            hour = hour + 1;
            futureHour = hour;
        }
    }

    // Update form with default start and end time
    // for a new event.
    startTimeLabel.setText("" + hour + ":" + String.format("%02d", minute) + " " + noonOrNight);
    startTimeLabel.setOnClickListener(this);
    endTimeLabel.setText("" + futureHour + ":" + String.format("%02d", futureMinute) + " " + noonOrNight);
    endTimeLabel.setOnClickListener(this);

    // Add click listener to checkboxes
    food.setOnClickListener(this);
    movie.setOnClickListener(this);
    outdoors.setOnClickListener(this);

    return rootView;
}

From source file:MailDateFormatter.java

/**
 * A method that returns a string rapresenting a date.
 *
 * @param date the date//from w  ww.ja v  a  2 s.com
 *
 * @param format the format as one of
 * FORMAT_MONTH_DAY,
 * FORMAT_MONTH_DAY_YEAR,
 * FORMAT_HOURS_MINUTES,
 * FORMAT_HOURS_MINUTES_SECONDS
 * FORMAT_DAY_MONTH
 * FORMAT_DAY_MONTH_YEAR
 * constants
 *
 * @param separator the separator to be used
 */
public static String getFormattedStringFromDate(Date date, int format, String separator) {

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    StringBuffer ret = new StringBuffer();

    switch (format) {
    case FORMAT_HOURS_MINUTES:
        //if pm and hour == 0 we want to write 12, not 0
        if (cal.get(Calendar.AM_PM) == Calendar.PM && cal.get(Calendar.HOUR) == 0) {
            ret.append("12");
        } else {
            ret.append(cal.get(Calendar.HOUR));
        }
        ret.append(separator).append(printTwoDigits(cal.get(Calendar.MINUTE))).append(getAMPM(cal));
        break;

    case FORMAT_HOURS_MINUTES_SECONDS:
        //if pm and hour == 0 we want to write 12, not 0
        if (cal.get(Calendar.AM_PM) == Calendar.PM && cal.get(Calendar.HOUR) == 0) {
            ret.append("12");
        } else {
            ret.append(cal.get(Calendar.HOUR));
        }
        ret.append(separator).append(printTwoDigits(cal.get(Calendar.MINUTE))).append(separator)
                .append(cal.get(Calendar.SECOND)).append(getAMPM(cal));
        break;

    case FORMAT_MONTH_DAY:
        ret.append(cal.get(Calendar.MONTH) + 1).append(separator).append(cal.get(Calendar.DAY_OF_MONTH));
        break;

    case FORMAT_DAY_MONTH:
        ret.append(cal.get(Calendar.DAY_OF_MONTH)).append(separator).append(cal.get(Calendar.MONTH) + 1);
        break;

    case FORMAT_MONTH_DAY_YEAR:
        ret.append(cal.get(Calendar.MONTH) + 1).append(separator).append(cal.get(Calendar.DAY_OF_MONTH))
                .append(separator).append(cal.get(Calendar.YEAR));
        break;

    case FORMAT_DAY_MONTH_YEAR:
        ret.append(cal.get(Calendar.DAY_OF_MONTH)).append(separator).append(cal.get(Calendar.MONTH) + 1)
                .append(separator).append(cal.get(Calendar.YEAR));
        break;

    default:
        //  Log.error("getFormattedStringFromDate: invalid format ("+
        //        format+")");
    }

    return ret.toString();
}

From source file:FirstStatMain.java

private void currentDateandTime() {
    Calendar cal = new GregorianCalendar();
    int day = cal.get(Calendar.MONTH);
    int month = cal.get(Calendar.DAY_OF_MONTH);
    int year = cal.get(Calendar.YEAR);
    int second = cal.get(Calendar.SECOND);
    int minute = cal.get(Calendar.MINUTE);
    int hour = cal.get(Calendar.HOUR);
    menuDate.setText("Today:" + month + "/" + day + "/" + year);
    menuDate.setForeground(Color.blue);
    menuTIme.setText("Time:" + hour + "/" + minute + "/" + second);
    menuTIme.setForeground(Color.red);
}

From source file:net.firejack.platform.api.statistics.StatisticsAPITests.java

@Test
public void checkStatisticsAPI() {
    OpenFlamePrincipal principal = OPFContext.getContext().getPrincipal();
    IUserInfoProvider user = principal.getUserInfoProvider();
    //=============== Log Entries ===============
    logger.info("Trying to read all log-entries...");
    ServiceResponse<LogEntry> logEntryResponse = OPFEngine.StatisticsService.readAllLogEntries();
    checkResponse(logEntryResponse);//from w  w w. ja  va 2s  . c o  m
    logger.info("logEntryResponse.getData().size() = " + logEntryResponse.getData().size());

    logger.info("Trying to find already existing test log entries.");
    logEntryResponse = searchTestLogEntries();
    int testEntriesCount = logEntryResponse.getData() == null ? 0 : logEntryResponse.getData().size();

    logger.info("Trying to create log entry");

    LogEntry logEntry1 = populateTestLogEntry(user, Boolean.TRUE);
    LogEntry logEntry2 = populateTestLogEntry(user, Boolean.FALSE);

    List<LogEntry> logEntriesToSave = new ArrayList<LogEntry>();
    logEntriesToSave.add(logEntry1);
    logEntriesToSave.add(logEntry2);

    ServiceRequest<LogEntry> request = new ServiceRequest<LogEntry>();
    request.setDataList(logEntriesToSave);

    ServiceResponse statusResponse = OPFEngine.StatisticsService.saveStatisticsBunch(request);
    checkResponse(statusResponse);

    logger.info("Trying to find just created log entries.");
    logEntryResponse = searchTestLogEntries();
    Assert.assertNotNull("logEntryResponse.getData() should not be null.", logEntryResponse.getData());
    Assert.assertTrue("testEntriesCount should be equal to " + (testEntriesCount + 2),
            logEntryResponse.getData().size() == testEntriesCount + 2);

    //================= Metrics =================
    logger.info("Trying to get count of already existent test metric tracks.");
    ServiceResponse<MetricsEntry> metricsResponse = searchTestMetrics();
    checkResponse(metricsResponse);
    int testMetricsCount = metricsResponse.getData() == null ? 0 : metricsResponse.getData().size();

    logger.info("Trying to save MetricsEntry...");
    MetricsEntry metricsEntry = new MetricsEntry();
    metricsEntry.setUserId(user.getId());
    metricsEntry.setUsername(user.getUsername());
    metricsEntry.setLookup(VAL_TEST_ACTION_LOOKUP);
    metricsEntry.setAverageExecutionTime(randomExecutionTime().doubleValue());
    metricsEntry.setAverageRequestSize(2000D);
    metricsEntry.setAverageResponseSize(2000D);
    metricsEntry.setMaxResponseTime(randomExecutionTime());
    metricsEntry.setMinResponseTime(randomExecutionTime());
    metricsEntry.setNumberOfInvocations(24L);
    metricsEntry.setSuccessRate(24D);
    Date hourlyDate = new Date();
    hourlyDate = DateUtils.truncate(hourlyDate, Calendar.HOUR);
    metricsEntry.setHourPeriod(hourlyDate.getTime());
    metricsEntry.setDayPeriod(DateUtils.truncate(hourlyDate, Calendar.DAY_OF_MONTH).getTime());
    Date weekPeriod = net.firejack.platform.core.utils.DateUtils.truncateDateToWeek(hourlyDate);
    metricsEntry.setWeekPeriod(weekPeriod.getTime());
    metricsEntry.setMonthPeriod(DateUtils.truncate(hourlyDate, Calendar.MONTH).getTime());

    ServiceRequest<MetricsEntry> metricsRequest = new ServiceRequest<MetricsEntry>(metricsEntry);
    statusResponse = OPFEngine.StatisticsService.saveMetricsEntry(metricsRequest);
    checkResponse(statusResponse);

    logger.info("Trying to get count of test metric tracks after saving one metric.");
    metricsResponse = searchTestMetrics();
    checkResponse(metricsResponse);
    Assert.assertNotNull("metricsResponse.getData() should nul be null", metricsResponse.getData());
    Assert.assertTrue("metricsResponse.getData().size() should be more or equal to " + testMetricsCount,
            metricsResponse.getData().size() >= testMetricsCount);

    logger.info("Trying to find metric by example...");
    metricsResponse = OPFEngine.StatisticsService.findMetricsEntryByExample(metricsRequest);
    checkResponse(metricsResponse);
    Assert.assertNotNull("metricsResponse.getData() should not be null.", metricsResponse.getData());
    logger.info("Tested all service methods successfully!");
}

From source file:it.govpay.web.rs.Check.java

private Sonda getSonda(BasicBD bd, CheckSonda checkSonda)
        throws SondaException, ServiceException, NotFoundException {
    Sonda sonda = SondaFactory.get(checkSonda.getName(), bd.getConnection(),
            bd.getJdbcProperties().getDatabase());
    if (sonda == null)
        throw new NotFoundException("Sonda con nome [" + checkSonda.getName() + "] non configurata");
    if (checkSonda.isCoda()) {
        long num = -1;
        if (Operazioni.check_ntfy.equals(checkSonda.getName())) {
            NotificheBD notBD = new NotificheBD(bd);
            num = notBD.countNotificheInAttesa();
        } else if (Operazioni.check_tracciati.equals(checkSonda.getName())) {
            TracciatiBD tracciatiBD = new TracciatiBD(bd);
            TracciatoFilter filter = tracciatiBD.newFilter();

            filter.addStatoTracciato(StatoTracciatoType.IN_CARICAMENTO);
            filter.addStatoTracciato(StatoTracciatoType.NUOVO);
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.HOUR, -6); //TODO parametrizzare

            filter.setDataCaricamentoMax(cal.getTime());
            num = tracciatiBD.count(filter);
        }/*from w  ww  .j  a v a2  s  .c om*/
        ((SondaCoda) sonda).aggiornaStatoSonda(num, bd.getConnection(), bd.getJdbcProperties().getDatabase());
    }
    return sonda;
}

From source file:org.motechproject.mobile.itests.MessageServiceImplITCase.java

/**
 * Test of sendPatientMessage method, of class MessageServiceImpl.
 *//*from  ww  w.j a v  a 2s .co  m*/
@Test
public void testSendPatientMessage() {
    System.out.println("sendPatientMessage");
    String messageId = "testId1";

    NameValuePair attrib = new NameValuePair("PatientFirstName", "Tester");
    NameValuePair attrib2 = new NameValuePair("DueDate", "now");
    NameValuePair[] personalInfo = new NameValuePair[] { attrib, attrib2 };

    Date serviceDate = new Date();
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, 1);
    Date endDate = cal.getTime();

    String patientNumber = testProps.getProperty("patientNumber", "000000000000");
    ContactNumberType patientNumberType = ContactNumberType.PERSONAL;
    MediaType messageType = MediaType.TEXT;
    MessageStatus result = client.sendPatientMessage(messageId, personalInfo, patientNumber, patientNumberType,
            "en", messageType, 2L, serviceDate, endDate, "123456789");
    assertEquals(result, MessageStatus.QUEUED);
}

From source file:com.floreantpos.actions.ClockInOutAction.java

private void performClockOut(User user) {
    try {/*ww  w  .  java  2 s .  c  o  m*/
        if (user == null) {
            return;
        }

        AttendenceHistoryDAO attendenceHistoryDAO = new AttendenceHistoryDAO();
        AttendenceHistory attendenceHistory = attendenceHistoryDAO.findHistoryByClockedInTime(user);
        if (attendenceHistory == null) {
            attendenceHistory = new AttendenceHistory();
            Date lastClockInTime = user.getLastClockInTime();
            Calendar c = Calendar.getInstance();
            c.setTime(lastClockInTime);
            attendenceHistory.setClockInTime(lastClockInTime);
            attendenceHistory.setClockInHour(Short.valueOf((short) c.get(Calendar.HOUR)));
            attendenceHistory.setUser(user);
            attendenceHistory.setTerminal(Application.getInstance().getTerminal());
            attendenceHistory.setShift(user.getCurrentShift());
        }

        Shift shift = user.getCurrentShift();
        Calendar calendar = Calendar.getInstance();

        user.doClockOut(attendenceHistory, shift, calendar);

        POSMessageDialog.showMessage(Messages.getString("ClockInOutAction.8") + user.getFirstName() + " " //$NON-NLS-1$//$NON-NLS-2$
                + user.getLastName() + Messages.getString("ClockInOutAction.10")); //$NON-NLS-1$
    } catch (Exception e) {
        POSMessageDialog.showError(Application.getPosWindow(), e.getMessage(), e);
    }
}

From source file:cn.mljia.common.notify.utils.DateUtils.java

/**
 * ???//w w w.  j a  v a  2 s  . c  o  m
 * 
 * @param date
 *            1
 * @param otherDate
 *            2
 * @param withUnit
 *            ??Calendar field?
 * @return 0, 0 ??0
 */
public static int compareTime(Date date, Date otherDate, int withUnit) {
    Calendar dateCal = Calendar.getInstance();
    dateCal.setTime(date);
    Calendar otherDateCal = Calendar.getInstance();
    otherDateCal.setTime(otherDate);

    dateCal.clear(Calendar.YEAR);
    dateCal.clear(Calendar.MONTH);
    dateCal.set(Calendar.DATE, 1);
    otherDateCal.clear(Calendar.YEAR);
    otherDateCal.clear(Calendar.MONTH);
    otherDateCal.set(Calendar.DATE, 1);
    switch (withUnit) {
    case Calendar.HOUR:
        dateCal.clear(Calendar.MINUTE);
        otherDateCal.clear(Calendar.MINUTE);
    case Calendar.MINUTE:
        dateCal.clear(Calendar.SECOND);
        otherDateCal.clear(Calendar.SECOND);
    case Calendar.SECOND:
        dateCal.clear(Calendar.MILLISECOND);
        otherDateCal.clear(Calendar.MILLISECOND);
    case Calendar.MILLISECOND:
        break;
    default:
        throw new IllegalArgumentException("withUnit ?? " + withUnit + " ????");
    }
    return dateCal.compareTo(otherDateCal);
}

From source file:fr.paris.lutece.plugins.workflow.modules.appointment.service.ICalService.java

/**
 * Send an appointment to a user by email.
 * @param strEmailAttendee Comma separated list of users that will attend
 *            the appointment/*from w w w  .j  av  a 2 s  . c o  m*/
 * @param strEmailOptionnal Comma separated list of users that will be
 *            invited to the appointment, but who are not required.
 * @param strSubject The subject of the appointment.
 * @param strBodyContent The body content that describes the appointment
 * @param strLocation The location of the appointment
 * @param strSenderName The name of the sender
 * @param strSenderEmail The email of the sender
 * @param appointment The appointment
 * @param bCreate True to notify the creation of the appointment, false to
 *            notify its removal
 */
public void sendAppointment(String strEmailAttendee, String strEmailOptionnal, String strSubject,
        String strBodyContent, String strLocation, String strSenderName, String strSenderEmail,
        Appointment appointment, boolean bCreate) {

    AppointmentSlot slot = AppointmentSlotHome.findByPrimaryKey(appointment.getIdSlot());
    Calendar calendarStart = new GregorianCalendar(Locale.FRENCH);

    calendarStart.setTime(appointment.getDateAppointment());
    calendarStart.add(Calendar.HOUR, slot.getStartingHour());
    calendarStart.add(Calendar.MINUTE, slot.getStartingMinute());

    int nAppDurationMinutes = ((slot.getEndingHour() - slot.getStartingHour()) * 60)
            + (slot.getEndingMinute() - slot.getStartingMinute());
    int nDurationAppointmentHours = nAppDurationMinutes / 60;
    int nDurationAppointmentMinutes = nAppDurationMinutes % 60;

    int nDurationAppointmentDays = nDurationAppointmentHours / 24;
    nDurationAppointmentHours %= 24;

    //       Dur duration = new Dur( nDurationAppointmentDays, nDurationAppointmentHours, nDurationAppointmentMinutes, 0 );

    //        TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
    //        TimeZone timezone = registry.getTimeZone("Europe/Paris");

    DateTime beginningDateTime = new DateTime(calendarStart.getTimeInMillis());
    beginningDateTime.setTimeZone(getParisZone());

    Calendar endCal = new GregorianCalendar();
    endCal.setTimeInMillis(calendarStart.getTimeInMillis());
    endCal.add(Calendar.MINUTE, nAppDurationMinutes);

    DateTime endingDateTime = new DateTime(endCal.getTimeInMillis());
    endingDateTime.setTimeZone(getParisZone());

    VEvent event = new VEvent(beginningDateTime, endingDateTime,
            (strSubject != null) ? strSubject : StringUtils.EMPTY);

    calendarStart.add(Calendar.MINUTE, nAppDurationMinutes);

    //  event.getProperties(  ).add( new DtEnd( endingDateTime ) );

    try {
        event.getProperties()
                .add(new Uid(Appointment.APPOINTMENT_RESOURCE_TYPE + appointment.getIdAppointment()));

        String strEmailSeparator = AppPropertiesService.getProperty(PROPERTY_MAIL_LIST_SEPARATOR, ";");
        if (StringUtils.isNotEmpty(strEmailAttendee)) {
            StringTokenizer st = new StringTokenizer(strEmailAttendee, strEmailSeparator);

            while (st.hasMoreTokens()) {
                addAttendee(event, st.nextToken(), true);
            }
        }

        if (StringUtils.isNotEmpty(strEmailOptionnal)) {
            StringTokenizer st = new StringTokenizer(strEmailOptionnal, strEmailSeparator);

            while (st.hasMoreTokens()) {
                addAttendee(event, st.nextToken(), false);
            }
        }

        Organizer organizer = new Organizer(strSenderEmail);
        organizer.getParameters().add(new Cn(strSenderName));
        event.getProperties().add(organizer);
        event.getProperties().add(new Location(strLocation));
        event.getProperties().add(new Description(strBodyContent));
    } catch (URISyntaxException e) {
        AppLogService.error(e.getMessage(), e);
    }

    net.fortuna.ical4j.model.Calendar iCalendar = new net.fortuna.ical4j.model.Calendar();
    iCalendar.getProperties().add(bCreate ? Method.REQUEST : Method.CANCEL);
    iCalendar.getProperties().add(new ProdId(AppPropertiesService.getProperty(PROPERTY_ICAL_PRODID)));
    iCalendar.getProperties().add(Version.VERSION_2_0);
    iCalendar.getProperties().add(CalScale.GREGORIAN);

    iCalendar.getComponents().add(event);

    MailService.sendMailCalendar(strEmailAttendee, strEmailOptionnal, null, strSenderName, strSenderEmail,
            (strSubject != null) ? strSubject : StringUtils.EMPTY, strBodyContent, iCalendar.toString(),
            bCreate);
}