Example usage for java.util Calendar AM_PM

List of usage examples for java.util Calendar AM_PM

Introduction

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

Prototype

int AM_PM

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

Click Source Link

Document

Field number for get and set indicating whether the HOUR is before or after noon.

Usage

From source file:com.etime.ETimeUtils.java

/**
 * Parse a Punch from a given string. The format is assumed to be "12:00AM". All other calendar fields are set
 * to the current days value. The day, month, year, timezone and other misc fields are set to the current days value.
 *
 * @param punchStr The String to be parsed for the punch
 * @return the parsed Punch//  ww  w.  j a v  a 2s.c  o m
 */
private static Punch getPunchFromString(String punchStr) {
    Punch punch = new Punch();
    Calendar calendar;
    Pattern punchPattern = Pattern.compile("(\\d+):(\\d+)(A|P)M");//Format is "12:00PM"
    Matcher punchMatcher = punchPattern.matcher(punchStr);

    if (!punchMatcher.find()) {
        return null;
    }

    int hour = Integer.parseInt(punchMatcher.group(1));
    int min = Integer.parseInt(punchMatcher.group(2));

    calendar = Calendar.getInstance();
    int hour24;
    if (punchMatcher.group(3).equals("A")) {
        calendar.set(Calendar.AM_PM, Calendar.AM);
        calendar.set(Calendar.HOUR, hour);
        if (hour == 12) {
            hour24 = 0;
        } else {
            hour24 = hour;
        }
    } else {
        calendar.set(Calendar.AM_PM, Calendar.PM);
        calendar.set(Calendar.HOUR, hour);

        if (hour != 12) {
            hour24 = hour + 12;
        } else {
            hour24 = hour;
        }
    }

    calendar.set(Calendar.HOUR_OF_DAY, hour24);
    calendar.set(Calendar.MINUTE, min);
    calendar.set(Calendar.SECOND, 0);
    punch.setCalendar(calendar);
    return punch;
}

From source file:org.kuali.coeus.sys.impl.scheduling.ScheduleServiceImpl.java

/**
 * This is helper method, wraps date with time accurately in java.util.Date (milliseconds).
 * /* w  w w .j  a  v  a2s . c o  m*/
 * @param date to be wrapped.
 * @param time to be added to date.
 * @return wrapped date & time.
 */
protected Date wrapTime(Date date, Time24HrFmt time) {
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(date);
    int hour = calendar.get(Calendar.HOUR);
    int min = calendar.get(Calendar.MINUTE);
    int am_pm = calendar.get(Calendar.AM_PM);
    if (am_pm == Calendar.AM) {
        date = DateUtils.addHours(date, -hour);
        date = DateUtils.addMinutes(date, -min);
    } else {
        date = DateUtils.addHours(date, -hour - 12);
        date = DateUtils.addMinutes(date, -min);
    }
    if (null != time) {
        date = DateUtils.addHours(date, new Integer(time.getHours()));
        date = DateUtils.addMinutes(date, new Integer(time.getMinutes()));
    }
    return date;
}

From source file:org.broadleafcommerce.common.web.BroadleafSandBoxResolverImpl.java

@Override
public SandBox resolveSandBox(WebRequest request, Site site) {
    Long previousSandBoxId = null;
    if (BLCRequestUtils.isOKtoUseSession(request)) {
        previousSandBoxId = (Long) request.getAttribute(SANDBOX_ID_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
    }/*from ww w .j  a va  2s  .com*/
    SandBox currentSandbox = null;
    if (!sandBoxPreviewEnabled) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Sandbox preview disabled. Setting sandbox to production");
        }
        request.setAttribute(SANDBOX_VAR, currentSandbox, WebRequest.SCOPE_REQUEST);
    } else if (crossAppAuthService != null && !crossAppAuthService.isAuthedFromAdmin()) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Sandbox preview attempted without authentication");
        }
        request.setAttribute(SANDBOX_VAR, currentSandbox, WebRequest.SCOPE_REQUEST);
    } else if (crossAppAuthService != null && crossAppAuthService.hasCsrPermission()) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Sandbox preview attempted in CSR mode");
        }
        request.setAttribute(SANDBOX_VAR, currentSandbox, WebRequest.SCOPE_REQUEST);
    } else {
        Long sandboxId = null;
        // Clear the sandBox - second parameter is to support legacy implementations.
        if ((request.getParameter("blClearSandBox") == null)
                && (request.getParameter("blSandboxDateTimeRibbonProduction") == null)) {
            sandboxId = lookupSandboxId(request);
        } else {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Removing sandbox from session.");
            }
            if (BLCRequestUtils.isOKtoUseSession(request)) {
                request.removeAttribute(SANDBOX_DATE_TIME_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
                request.removeAttribute(SANDBOX_ID_VAR, WebRequest.SCOPE_GLOBAL_SESSION);
            }
            SystemTime.resetLocalTimeSource();
        }
        if (sandboxId != null) {
            if (previousSandBoxId != null && !previousSandBoxId.equals(sandboxId)) {
                request.setAttribute(BroadleafRequestProcessor.REPROCESS_PARAM_NAME, true,
                        WebRequest.SCOPE_REQUEST);
            }

            currentSandbox = sandBoxDao.retrieve(sandboxId);
            request.setAttribute(SANDBOX_VAR, currentSandbox, WebRequest.SCOPE_REQUEST);
            if (currentSandbox != null && !SandBoxType.PRODUCTION.equals(currentSandbox.getSandBoxType())) {
                setContentTime(request);
            }
        }

        //            if (currentSandbox == null && site != null) {
        //                currentSandbox = site.getProductionSandbox();
        //            }
    }

    if (LOG.isTraceEnabled()) {
        if (currentSandbox != null) {
            LOG.trace("Serving request using sandbox: " + currentSandbox);
        } else {
            LOG.trace("Serving request without a sandbox.");
        }
    }

    Date currentSystemDateTime = SystemTime.asDate(true);
    Calendar sandboxDateTimeCalendar = Calendar.getInstance();
    sandboxDateTimeCalendar.setTime(currentSystemDateTime);
    request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_DATE_PARAM,
            CONTENT_DATE_DISPLAY_FORMATTER.format(currentSystemDateTime), WebRequest.SCOPE_REQUEST);
    request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_HOURS_PARAM,
            CONTENT_DATE_DISPLAY_HOURS_FORMATTER.format(currentSystemDateTime), WebRequest.SCOPE_REQUEST);
    request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_MINUTES_PARAM,
            CONTENT_DATE_DISPLAY_MINUTES_FORMATTER.format(currentSystemDateTime), WebRequest.SCOPE_REQUEST);
    request.setAttribute(SANDBOX_DISPLAY_DATE_TIME_AMPM_PARAM, sandboxDateTimeCalendar.get(Calendar.AM_PM),
            WebRequest.SCOPE_REQUEST);
    return currentSandbox;
}

From source file:org.kuali.kfs.pdp.service.impl.FormatServiceImpl.java

/**
 * @see org.kuali.kfs.pdp.service.FormatService#startFormatProcess(org.kuali.rice.kim.bo.Person, java.lang.String,
 *      java.util.List, java.util.Date, java.lang.String)
 *//*w w w  .  j  a va 2  s  .  c o  m*/
@Override
public FormatProcessSummary startFormatProcess(Person user, String campus, List<CustomerProfile> customers,
        Date paydate, String paymentTypes) {
    LOG.debug("startFormatProcess() started");

    for (CustomerProfile element : customers) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("startFormatProcess() Customer: " + element);
        }
    }

    // Create the process
    Date d = new Date();
    PaymentProcess paymentProcess = new PaymentProcess();
    paymentProcess.setCampusCode(campus);
    paymentProcess.setProcessUser(user);
    paymentProcess.setProcessTimestamp(new Timestamp(d.getTime()));

    this.businessObjectService.save(paymentProcess);

    // add an entry in the format process table (to lock the format process)
    FormatProcess formatProcess = new FormatProcess();

    formatProcess.setPhysicalCampusProcessCode(campus);
    formatProcess.setBeginFormat(dateTimeService.getCurrentTimestamp());
    formatProcess.setPaymentProcIdentifier(paymentProcess.getId().intValue());

    this.businessObjectService.save(formatProcess);

    Timestamp now = new Timestamp((new Date()).getTime());
    java.sql.Date sqlDate = new java.sql.Date(paydate.getTime());
    Calendar c = Calendar.getInstance();
    c.setTime(sqlDate);
    c.set(Calendar.HOUR, 11);
    c.set(Calendar.MINUTE, 59);
    c.set(Calendar.SECOND, 59);
    c.set(Calendar.MILLISECOND, 59);
    c.set(Calendar.AM_PM, Calendar.PM);
    Timestamp paydateTs = new Timestamp(c.getTime().getTime());

    if (LOG.isDebugEnabled()) {
        LOG.debug("startFormatProcess() last update = " + now);
        LOG.debug("startFormatProcess() entered paydate = " + paydate);
        LOG.debug("startFormatProcess() actual paydate = " + paydateTs);
    }
    PaymentStatus format = this.businessObjectService.findBySinglePrimaryKey(PaymentStatus.class,
            PdpConstants.PaymentStatusCodes.FORMAT);

    List customerIds = new ArrayList();
    for (Iterator iter = customers.iterator(); iter.hasNext();) {
        CustomerProfile element = (CustomerProfile) iter.next();
        customerIds.add(element.getId());
    }

    // Mark all of them ready for format
    Iterator groupIterator = formatPaymentDao.markPaymentsForFormat(customerIds, paydateTs, paymentTypes);

    while (groupIterator.hasNext()) {
        PaymentGroup paymentGroup = (PaymentGroup) groupIterator.next();
        paymentGroup.setLastUpdate(paydateTs);// delete this one
        paymentGroup.setPaymentStatus(format);
        paymentGroup.setProcess(paymentProcess);
        businessObjectService.save(paymentGroup);
    }

    // summarize them
    FormatProcessSummary preFormatProcessSummary = new FormatProcessSummary();
    Iterator<PaymentGroup> iterator = this.paymentGroupService.getByProcess(paymentProcess);

    while (iterator.hasNext()) {
        PaymentGroup paymentGroup = iterator.next();
        preFormatProcessSummary.add(paymentGroup);
    }

    // if no payments found for format clear the format process
    if (preFormatProcessSummary.getProcessSummaryList().size() == 0) {
        LOG.debug("startFormatProcess() No payments to process.  Format process ending");
        clearUnfinishedFormat(paymentProcess.getId().intValue());// ?? maybe call end format process
    }

    return preFormatProcessSummary;
}

From source file:com.versobit.weatherdoge.WeatherUtil.java

private static String convertYahooCode(String code, String weatherTime, String sunrise, String sunset) {
    Date weatherDate = new Date();
    try {//  w w  w .j  av  a  2 s .co  m
        weatherDate = YAHOO_DATE_FORMAT.parse(weatherTime);
    } catch (ParseException ex) {
        Log.e(TAG, "Yahoo date format failed!", ex);
    }
    Calendar weatherCal = new GregorianCalendar();
    Calendar sunriseCal = new GregorianCalendar();
    Calendar sunsetCal = new GregorianCalendar();
    weatherCal.setTime(weatherDate);
    sunriseCal.setTime(weatherDate);
    sunsetCal.setTime(weatherDate);

    Matcher sunriseMatch = YAHOO_TIME.matcher(sunrise);
    Matcher sunsetMatch = YAHOO_TIME.matcher(sunset);
    if (!sunriseMatch.matches() || !sunsetMatch.matches()) {
        Log.e(TAG, "Failed to find sunrise/sunset. Using defaults.");
        sunriseMatch = YAHOO_TIME.matcher("6:00 am");
        sunsetMatch = YAHOO_TIME.matcher("6:00 pm");
        sunriseMatch.matches();
        sunsetMatch.matches();
    }
    // Set the sunrise to the correct hour and minute of the same day
    sunriseCal.set(Calendar.HOUR, Integer.parseInt(sunriseMatch.group(1)));
    sunriseCal.set(Calendar.MINUTE, Integer.parseInt(sunriseMatch.group(2)));
    sunriseCal.set(Calendar.SECOND, 0);
    sunriseCal.set(Calendar.MILLISECOND, 0);
    sunriseCal.set(Calendar.AM_PM, "am".equals(sunriseMatch.group(3)) ? Calendar.AM : Calendar.PM);

    // Set the sunset to the correct hour and minute of the same day
    sunsetCal.set(Calendar.HOUR, Integer.parseInt(sunsetMatch.group(1)));
    sunsetCal.set(Calendar.MINUTE, Integer.parseInt(sunsetMatch.group(2)));
    sunsetCal.set(Calendar.SECOND, 0);
    sunsetCal.set(Calendar.MILLISECOND, 0);
    sunsetCal.set(Calendar.AM_PM, "am".equals(sunsetMatch.group(3)) ? Calendar.AM : Calendar.PM);

    boolean isDaytime = true;
    if (weatherCal.before(sunriseCal) || weatherCal.after(sunsetCal)) {
        isDaytime = false;
    }

    String owmCode = "01";
    switch (Integer.parseInt(code)) {
    // Thunderstorms
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 17:
    case 37:
    case 38:
    case 39:
    case 45:
    case 47:
        owmCode = "11";
        break;
    // Snow
    case 5:
    case 7:
    case 13:
    case 14:
    case 15:
    case 16:
    case 18:
    case 41:
    case 42:
    case 43:
    case 46:
        owmCode = "13";
        break;
    // Rain
    case 6:
    case 10:
    case 35:
        owmCode = "09";
        break;
    // Light-ish Rain
    case 8:
    case 9:
    case 11:
    case 12:
    case 40:
        owmCode = "10";
        break;
    // Fog
    case 19:
    case 20:
    case 21:
    case 22:
        owmCode = "50";
        break;
    // Cloudy
    case 27:
    case 28:
        owmCode = "04";
        break;
    // (Other) Cloudy
    case 26:
        owmCode = "03";
        break;
    // Partly Cloudy
    case 23:
    case 24:
    case 25:
    case 29:
    case 30:
    case 44:
        owmCode = "02";
        break;
    // Clear
    case 31:
    case 32:
    case 33:
    case 34:
    case 36:
        owmCode = "01";
        break;
    }
    return owmCode + (isDaytime ? "d" : "n");
}

From source file:com.ibm.pickmeup.activities.MapActivity.java

/**
 * Update map with the new coordinates for the driver
 * @param intent containing driver coordinates
 *//*from  w w  w .  j  av  a 2  s  .c om*/
private void updateMap(final Intent intent) {
    // not logging entry as it will flood the logs

    // getting driver LatLng values from the intent
    final LatLng driverLatLng = new LatLng(intent.getFloatExtra(Constants.LATITUDE, 0),
            intent.getFloatExtra(Constants.LONGITUDE, 0));

    // create driver marker if it doesn't exist and move the camera accordingly
    if (driverMarker == null) {
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(driverLatLng, 10));
        driverMarker = mMap.addMarker(new MarkerOptions().position(driverLatLng)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_driver)));
        return;
    }

    // update driver location with LatLng
    driverLocation.setLatitude(driverLatLng.latitude);
    driverLocation.setLongitude(driverLatLng.longitude);

    // calculate current distance to the passenger
    float distance = passengerLocation.distanceTo(driverLocation) / 1000;

    // set the distance text
    distanceDetails.setText(String.format(getResources().getString(R.string.distance_with_value), distance));

    // calculating ETA - we are assuming here that the car travels at 20mph to simplify the calculations
    calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, Math.round(distance / 20 * 60));

    // set AM/PM to a relevant value
    AM_PM = getString(R.string.am);
    if (calendar.get(Calendar.AM_PM) == 1) {
        AM_PM = getString(R.string.pm);
    }

    // format ETA string to HH:MM
    String eta = String.format(getResources().getString(R.string.eta_with_value),
            calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), AM_PM);

    // set the ETA text
    etaDetails.setText(eta);

    // as we are throttling updates to the coordinates, we might need to smooth out the moving
    // of the driver's marker. To do so we are going to draw temporary markers between the
    // previous and the current coordinates. We are going to use interpolation for this and
    // use handler/looper to set the marker's position

    // get hold of the handler
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();

    // get map projection and the driver's starting point
    Projection proj = mMap.getProjection();
    Point startPoint = proj.toScreenLocation(driverMarker.getPosition());
    final LatLng startLatLng = proj.fromScreenLocation(startPoint);
    final long duration = 150;

    // create new Interpolator
    final Interpolator interpolator = new LinearInterpolator();

    // post a Runnable to the handler
    handler.post(new Runnable() {
        @Override
        public void run() {
            // calculate how soon we need to redraw the marker
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);
            double lng = t * intent.getFloatExtra(Constants.LONGITUDE, 0) + (1 - t) * startLatLng.longitude;
            double lat = t * intent.getFloatExtra(Constants.LATITUDE, 0) + (1 - t) * startLatLng.latitude;

            // set the driver's marker position
            driverMarker.setPosition(new LatLng(lat, lng));
            if (t < 1.0) {
                handler.postDelayed(this, 10);
            }
        }
    });
}

From source file:com.etime.ETimeActivity.java

/**
 * Update the curStatus button with most recent data from the users
 * time card.//w  w w  . java 2s .com
 */
private void updateCurStatusBtn() {
    StringBuilder sb = new StringBuilder("Clocked ");
    Punch lastPunch;
    Calendar lastPunchCalendar;
    int minute;

    if (punches.isEmpty()) {
        return;
    }

    lastPunch = punches.get(punches.size() - 1);
    if (lastPunch.isClockIn()) {
        sb.append("in ");
    } else {
        sb.append("out ");
    }

    sb.append("at ");
    lastPunchCalendar = lastPunch.getCalendar();
    sb.append(Integer.toString(getHourFromCalendar(lastPunchCalendar))).append(":");

    minute = lastPunch.getCalendar().get(Calendar.MINUTE);
    if (minute < 10) {
        sb.append("0");
    }
    sb.append(Integer.toString(minute));

    if (lastPunchCalendar.get(Calendar.AM_PM) == Calendar.AM) {
        sb.append(" AM");
    } else {
        sb.append(" PM");
    }

    curStatus.setText(sb.toString());
}

From source file:com.rockagen.commons.util.CommUtil.java

/**
 * Return the next day's date and time 00:00:00 start date
 *
 * @param date Date// www  . ja  va2  s . c o m
 * @return next day begin
 */
public static Date nextDayBegin(Date date) {
    Calendar cal = getCalendar(date);
    cal.add(Calendar.DATE, 1); // next day's am O0:00:00
    cal.set(Calendar.AM_PM, Calendar.AM);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    return cal.getTime();
}

From source file:com.rockagen.commons.util.CommUtil.java

/**
 * Return the next month's date and time 00:00:00 start date
 *
 * @param date Date/* w  ww  .j a  v  a 2s  .c  om*/
 * @return next month begin
 */
public static Date nextMonthBegin(Date date) {
    Calendar cal = getCalendar(date);
    cal.set(Calendar.DAY_OF_MONTH, 1); // next month's am O0:00:00
    cal.add(Calendar.MONTH, 1);

    cal.set(Calendar.AM_PM, Calendar.AM);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    return cal.getTime();
}

From source file:me.crime.database.Crime.java

/**
  * //from   ww w  . j  a  v a2 s. c o  m
  */
 public void save() {
     CrimeDao dao = CrimeDao.class.cast(DaoBeanFactory.create().getDaoBean(CrimeDao.class));

     try {

         if (this.getStartDate() == null && this.getCounty().compareTo("Vienna") == 0) {
             String name = this.getFile().substring(0, this.getFile().indexOf('.'));

             String[] date = name.split("-");

             Calendar cal = Calendar.getInstance();

             cal.set(Calendar.MONTH, Integer.parseInt(date[0]));
             cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date[1]));
             cal.set(Calendar.YEAR, Integer.parseInt(date[2]));
             cal.set(Calendar.HOUR, 12);
             cal.set(Calendar.MINUTE, 0);
             cal.set(Calendar.SECOND, 0);
             cal.set(Calendar.MILLISECOND, 0);
             cal.set(Calendar.AM_PM, 0);

             this.setStartDate(cal);
         } else if (this.getStartDate() == null) {
             this.setStartDate(Calendar.getInstance());
         } else if (this.getStartDate().get(Calendar.YEAR) < 1999) {
             this.getStartDate().set(Calendar.YEAR, 1999);
         } else if (this.getStartDate().get(Calendar.YEAR) > 2009) {
             this.getStartDate().set(Calendar.YEAR, 2009);
         }

         if (isValidState(this.getAddress().getState())) {

             double dts = this.getStartDate().getTimeInMillis() / 86400000.0; // divide milliseconds per day to get
             // days.fraction_of_day
             double dayOrd = Math.floor(dts); // truncate to get whole days
             double timeOrd = (dts - dayOrd) * 24; // track time as hour.fraction_of_hour

             this.setTime(timeOrd);

             AddressDao locDao = AddressDao.class.cast(DaoBeanFactory.create().getDaoBean(AddressDao.class));

             Address location = locDao.loadAddress(this.getAddress().getLocation());
             if (location != null) {
                 this.setAddress(location);
             } else {
                 locDao.save(this.getAddress());
             }

             dao.save(this);
         }

     } catch (SQLException e) {

         log_.warn("Unable to save crime: " + this.getCrimeNumber() + "removing arrested");
         try {
             dao.save(this);
         } catch (SQLException e1) {
             log_.error("Unable to save crime: " + this.getCrimeNumber(), e);
         }

     }
 }