Example usage for java.text DateFormat getTimeInstance

List of usage examples for java.text DateFormat getTimeInstance

Introduction

In this page you can find the example usage for java.text DateFormat getTimeInstance.

Prototype

public static final DateFormat getTimeInstance(int style, Locale aLocale) 

Source Link

Document

Gets the time formatter with the given formatting style for the given locale.

Usage

From source file:org.y20k.trackbook.MainActivityTrackFragment.java

private void displayTrack() {
    GeoPoint position;/*ww w .  java 2s  . c  om*/

    if (mTrack != null) {
        // set end of track as position
        Location lastLocation = mTrack.getWayPointLocation(mTrack.getSize() - 1);
        position = new GeoPoint(lastLocation.getLatitude(), lastLocation.getLongitude());

        String recordingStart = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault())
                .format(mTrack.getRecordingStart()) + " "
                + DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault())
                        .format(mTrack.getRecordingStart());
        String recordingStop = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault())
                .format(mTrack.getRecordingStop()) + " "
                + DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault())
                        .format(mTrack.getRecordingStop());

        // populate views
        mDistanceView.setText(mTrack.getTrackDistance());
        mStepsView.setText(String.valueOf(Math.round(mTrack.getStepCount())));
        mWaypointsView.setText(String.valueOf(mTrack.getWayPoints().size()));
        mDurationView.setText(mTrack.getTrackDuration());
        mRecordingStartView.setText(recordingStart);
        mRecordingStopView.setText(recordingStop);

        // draw track on map
        drawTrackOverlay(mTrack);
    } else {
        position = new GeoPoint(DEFAULT_LATITUDE, DEFAULT_LONGITUDE);
    }

    // center map over position
    mController.setCenter(position);

}

From source file:org.agiso.tempel.Tempel.java

/**
 * /* w  w w  . j  a  v  a  2 s  .c o  m*/
 * 
 * @param properties
 * @throws Exception 
 */
private Map<String, Object> addRuntimeProperties(Map<String, Object> properties) throws Exception {
    Map<String, Object> props = new HashMap<String, Object>();

    // Okrelanie lokalizacji daty/czasu uywanej do wypenienia paramtrw szablonw
    // zawierajcych dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL:
    Locale date_locale;
    if (properties.containsKey(UP_DATE_LOCALE)) {
        date_locale = LocaleUtils.toLocale((String) properties.get(UP_DATE_LOCALE));
        Locale.setDefault(date_locale);
    } else {
        date_locale = Locale.getDefault();
    }

    TimeZone time_zone;
    if (properties.containsKey(UP_TIME_ZONE)) {
        time_zone = TimeZone.getTimeZone((String) properties.get(UP_DATE_LOCALE));
        TimeZone.setDefault(time_zone);
    } else {
        time_zone = TimeZone.getDefault();
    }

    // Wyznaczanie daty, na podstawie ktrej zostan wypenione parametry szablonw
    // przechowujce dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL.
    // Odbywa si w oparciu o wartoci parametrw 'date_format' i 'date'. Parametr
    // 'date_format' definiuje format uywany do parsowania acucha reprezentujcego
    // dat okrelon parametrem 'date'. Parametr 'date_format' moe nie by okrelony.
    // W takiej sytuacji uyty jest format DateFormat.LONG aktywnej lokalizacji (tj.
    // systemowej, ktra moe by przedefiniowana przez parametr 'date_locale'), ktry
    // moe by przedefiniowany przez parametry 'date_format_long' i 'time_format_long':
    Calendar calendar = Calendar.getInstance(date_locale);
    if (properties.containsKey(RP_DATE)) {
        String date_string = (String) properties.get(RP_DATE);
        if (properties.containsKey(RP_DATE_FORMAT)) {
            String date_format = (String) properties.get(RP_DATE_FORMAT);
            DateFormat formatter = new SimpleDateFormat(date_format);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        } else if (properties.containsKey(UP_DATE_FORMAT_LONG) && properties.containsKey(UP_TIME_FORMAT_LONG)) {
            // TODO: Zaoenie, e format data-czas jest zoony z acucha daty i czasu rozdzelonych spacj:
            // 'UP_DATE_FORMAT_LONG UP_TIME_FORMAT_LONG'
            DateFormat formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG) + " "
                    + (String) properties.get(UP_TIME_FORMAT_LONG), date_locale);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        } else {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG,
                    date_locale);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        }
    }

    // Jeli nie okrelono, wypenianie parametrw przechowujcych poszczeglne
    // skadniki daty, tj. rok, miesic i dzie:
    if (!properties.containsKey(TP_YEAR)) {
        props.put(TP_YEAR, calendar.get(Calendar.YEAR));
    }
    if (!properties.containsKey(TP_MONTH)) {
        props.put(TP_MONTH, calendar.get(Calendar.MONTH));
    }
    if (!properties.containsKey(TP_DAY)) {
        props.put(TP_DAY, calendar.get(Calendar.DAY_OF_MONTH));
    }

    // Jeli nie okrelono, wypenianie parametrw przechowujcych dat i czas w
    // formatach SHORT, MEDIUM, LONG i FULL (na podstawie wyznaczonej lokalizacji):
    Date date = calendar.getTime();
    if (!properties.containsKey(TP_DATE_SHORT)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_SHORT)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_SHORT), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.SHORT, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_SHORT, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_MEDIUM)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_MEDIUM)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_MEDIUM), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_MEDIUM, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_LONG)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_LONG)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.LONG, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_LONG, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_FULL)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_FULL)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_FULL), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.FULL, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_FULL, formatter.format(date));
    }

    if (!properties.containsKey(TP_TIME_SHORT)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_SHORT)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_SHORT), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.SHORT, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_SHORT, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_MEDIUM)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_MEDIUM)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_MEDIUM), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_MEDIUM, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_LONG)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_LONG)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_LONG), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.LONG, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_LONG, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_FULL)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_FULL)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_FULL), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.FULL, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_FULL, formatter.format(date));
    }

    return props;
}

From source file:io.bitsquare.gui.util.BSFormatter.java

public String formatDateTime(Date date) {
    if (date != null) {
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
        DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
        return dateFormatter.format(date) + " " + timeFormatter.format(date);
    } else {/*ww w  . j  a v a  2 s.c o  m*/
        return "";
    }
}

From source file:io.bitsquare.gui.util.BSFormatter.java

public String formatDateTimeSpan(Date dateFrom, Date dateTo) {
    if (dateFrom != null && dateTo != null) {
        DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
        DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
        return dateFormatter.format(dateFrom) + " " + timeFormatter.format(dateFrom) + " - "
                + timeFormatter.format(dateTo);
    } else {//from ww w.  ja va  2s .  co m
        return "";
    }
}

From source file:io.bitsquare.gui.util.BSFormatter.java

public String formatTime(Date date) {
    if (date != null) {
        DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
        return timeFormatter.format(date);
    } else {// w  ww  .j a va2 s  . co m
        return "";
    }
}

From source file:com.mg.framework.utils.MiscUtils.java

/**
 *  ? ?  ?? ?  <code>DATE, DATETIME, TIME</code>
 *
 * @param value     /* w w w . j a v a2 s  . com*/
 * @param metadata 
 * @param locale   
 * @return ? ?  ? ? ? <code>value == null</code>
 * @throws NullPointerException ? <code>metadata == null</code>
 */
public static String getDateTextRepresentation(Date value, FieldMetadata metadata, Locale locale) {
    if (value == null || DateTimeUtils.isBoundDateValue(value))
        return StringUtils.EMPTY_STRING;
    if (metadata == null)
        return value.toString();

    DateFormat df;
    switch (metadata.getBuiltInType()) {
    case DATE:
        df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
        break;
    case DATETIME:
        df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
        break;
    case TIME:
        df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
        break;
    default:
        return value.toString();
    }
    return df.format(value);
}

From source file:com.redhat.rhn.common.localization.LocalizationService.java

/**
 * Format the date based on the locale and convert it to a String to
 * display. Uses DateFormat.SHORT. Example: 2004-12-10 13:20:00 PST
 *
 * Also includes the timezone of the current User if there is one
 *
 * @param date Date to format.//from   w w  w .ja  v a 2 s.  c om
 * @param locale Locale to use for formatting.
 * @return String representation of given date in given locale.
 */
public String formatDate(Date date, Locale locale) {
    // Example: 2004-12-10 13:20:00 PST
    StringBuilder dbuff = new StringBuilder();
    DateFormat dateI = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    dateI.setTimeZone(determineTimeZone());
    DateFormat timeI = DateFormat.getTimeInstance(DateFormat.LONG, locale);
    timeI.setTimeZone(determineTimeZone());

    dbuff.append(dateI.format(date));
    dbuff.append(" ");
    dbuff.append(timeI.format(date));

    return getDebugVersionOfString(dbuff.toString());
}

From source file:desmoj.extensions.grafic.util.Plotter.java

/**
 * configure domainAxis (label, timeZone, locale, tick labels)
 * of time-series chart//from www  .  jav  a 2s  .  co  m
 * @param dateAxis
 */
private void configureDomainAxis(DateAxis dateAxis) {
    if (this.begin != null)
        dateAxis.setMinimumDate(this.begin);
    if (this.end != null)
        dateAxis.setMaximumDate(this.end);
    dateAxis.setTimeZone(this.timeZone);

    Date dateMin = dateAxis.getMinimumDate();
    Date dateMax = dateAxis.getMaximumDate();
    //DateFormat formatter = new SimpleDateFormat("d.MM.yyyy HH:mm:ss.SSS");;
    DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM, locale);
    String label = "Time: " + formatter.format(dateMin) + " .. " + formatter.format(dateMax);
    formatter = new SimpleDateFormat("z");
    label += " " + formatter.format(dateMax);
    dateAxis.setLabel(label);

    TimeInstant max = new TimeInstant(dateMax);
    TimeInstant min = new TimeInstant(dateMin);
    TimeSpan diff = TimeOperations.diff(max, min);

    if (TimeSpan.isLongerOrEqual(diff, new TimeSpan(1, TimeUnit.DAYS)))
        formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
    else if (TimeSpan.isLongerOrEqual(diff, new TimeSpan(1, TimeUnit.HOURS)))
        formatter = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
    else if (TimeSpan.isLongerOrEqual(diff, new TimeSpan(1, TimeUnit.MINUTES)))
        formatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
    else
        formatter = new SimpleDateFormat("HH:mm:ss.SSS");
    dateAxis.setDateFormatOverride(formatter);
    dateAxis.setVerticalTickLabels(true);
}

From source file:gov.opm.scrd.batchprocessing.jobs.BatchProcessingJob.java

/**
 * Do execution./*from ww w  . ja v a  2s .c o  m*/
 *
 * @param procMessage The process message. Used to build the mail message.
 * @return true if execution is successful; false to retry.
 * @throws BatchProcessingException If major error occurred.
 * @throes OPMException if there is any error during auditing
 */
private boolean doExecute(StringBuilder procMessage) throws BatchProcessingException, OPMException {
    // Reset
    reset();

    Date now = new Date(SysTime.instance.now());

    procMessage.append("Service Credit Batch started at ");
    procMessage.append(DateFormat.getTimeInstance(DateFormat.LONG, Locale.US).format(now));
    procMessage.append(" on ");
    procMessage.append(DateFormat.getDateInstance(DateFormat.LONG, Locale.US).format(now));
    procMessage.append(". Batch done at @#$%EndingTime%$#@.");
    procMessage.append(CRLF).append(CRLF);

    try {
        // Initialize the batchProcessUser
        List<User> list = entityManager.createQuery(JPQL_QUERY_USER_BY_USERNAME, User.class)
                .setParameter("username", currentUserName).getResultList();

        if (list.isEmpty()) {
            throw new AuthorizationException("Batch process user [" + currentUserName + "] is not found");
        }

        batchProcessUser = list.get(0);

        // Authorize
        securityService.authorize(currentUserName,
                Arrays.asList(new String[] { batchProcessUser.getRole().getName() }), "batchProcessingJob");
    } catch (AuthorizationException e) {
        logger.error("User " + currentUserName + " is not allowed to run the batch service.", e);
        procMessage.append("User ");
        procMessage.append(currentUserName);
        procMessage.append(" is not allowed to run the batch service. ");
        if (batchProcessUser == null) {
            procMessage.append("He does not exist. ");
        } else {
            procMessage.append("He is in the ").append(batchProcessUser.getRole().getName())
                    .append(" group instead of the System role. ");
        }
        procMessage.append("This is a serious configuration error. Call the Program Manager or DBA. ");
        notifyByEmail(procMessage.toString(), "Service Credit User Violation", "ERROR");
        savePaymentStatusPrint(procMessage.toString());
        return false;
    } catch (OPMException e) {
        throw new BatchProcessingException("Database error authorizing batch user.", e);
    } catch (PersistenceException e) {
        throw new BatchProcessingException("Database error authorizing batch user.", e);
    }

    // Initialize today's audit batch
    initTodayAuditBatch(now);

    // Is now holiday
    boolean isNowHoliday = isNowHoliday(now);
    logger.info("Is today holiday : " + isNowHoliday);

    batchPhase = BatchPhase.FILE_IMPORT;

    // Import files
    if (!importFiles(now, isNowHoliday)) {
        savePaymentStatusPrint(procMessage.toString());
        return false;
    }

    // Clean old files
    File toCleanDirectory = new File(directoryToClean);
    logger.info("Start cleaning old files in: " + toCleanDirectory);
    cleanOutOldFiles(toCleanDirectory);
    logger.info("End cleaning old files in: " + toCleanDirectory);

    if (!isNowHoliday) {
        batchPhase = BatchPhase.BILL_PROCESS;
        logger.info("Start Bill Processing.");

        boolean noMinorError = true;

        // Process bills
        try {
            entityManager.clear();
            billProcessor.processBills(todayAuditBatch.getId(), procMessage, 0, 0, 0, 0, 0);
        } catch (BillProcessingException e) {
            throw new BatchProcessingException(e.getMessage(), e);
        }
        logger.info("End Bill Processing.");

        // BatchDailyAccountUpdate
        logger.info("Start daily account updating.");
        noMinorError = batchDailyAccountUpdate(procMessage) && noMinorError;
        logger.info("End daily account updating.");

        // Make GL files
        File glFileDirectory = new File(glDirectory);
        logger.info("Start making GL file: " + glFileDirectory);
        noMinorError = makeGLFile(glFileDirectory, procMessage, now) && noMinorError;
        logger.info("End making GL file: " + glFileDirectory);

        // Notify process email
        String subject = noMinorError ? "Service Credit Nightly Batch: Good"
                : "Service Credit Nightly Batch: Warning!";
        savePaymentStatusPrint(procMessage.toString());
        notifyByEmail(procMessage.toString(), subject, "BillProcessing");
    }

    return true;
}

From source file:org.opencms.workflow.CmsExtendedWorkflowManager.java

/**
 * Generates the name for a new workflow project based on the user for whom it is created.<p>
 *
 * @param userCms the user's current CMS context
 * @param shortTime if true, the short time format will be used, else the medium time format
 *
 * @return the workflow project name/*from   w  w w .  j  a  v a2  s.  co m*/
 */
protected String generateProjectName(CmsObject userCms, boolean shortTime) {

    CmsUser user = userCms.getRequestContext().getCurrentUser();
    long time = System.currentTimeMillis();
    Date date = new Date(time);
    OpenCms.getLocaleManager();
    Locale locale = CmsLocaleManager.getDefaultLocale();
    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
    DateFormat timeFormat = DateFormat.getTimeInstance(shortTime ? DateFormat.SHORT : DateFormat.MEDIUM,
            locale);
    String dateStr = dateFormat.format(date) + " " + timeFormat.format(date);
    String username = user.getName();
    String result = Messages.get().getBundle(locale).key(Messages.GUI_WORKFLOW_PROJECT_NAME_2, username,
            dateStr);
    result = result.replaceAll("/", "|");

    return result;
}