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:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

private String doConvertToString(Map<String, Object> context, Object value) {
    String result = null;//from  www. j  a  v a2s .co m

    if (value instanceof int[]) {
        int[] x = (int[]) value;
        List<Integer> intArray = new ArrayList<Integer>(x.length);

        for (int aX : x) {
            intArray.add(Integer.valueOf(aX));
        }

        result = StringUtils.join(intArray, ", ");
    } else if (value instanceof long[]) {
        long[] x = (long[]) value;
        List<Long> longArray = new ArrayList<Long>(x.length);

        for (long aX : x) {
            longArray.add(Long.valueOf(aX));
        }

        result = StringUtils.join(longArray, ", ");
    } else if (value instanceof double[]) {
        double[] x = (double[]) value;
        List<Double> doubleArray = new ArrayList<Double>(x.length);

        for (double aX : x) {
            doubleArray.add(new Double(aX));
        }

        result = StringUtils.join(doubleArray, ", ");
    } else if (value instanceof boolean[]) {
        boolean[] x = (boolean[]) value;
        List<Boolean> booleanArray = new ArrayList<Boolean>(x.length);

        for (boolean aX : x) {
            booleanArray.add(new Boolean(aX));
        }

        result = StringUtils.join(booleanArray, ", ");
    } else if (value instanceof Date) {
        DateFormat df = null;
        if (value instanceof java.sql.Time) {
            df = DateFormat.getTimeInstance(DateFormat.MEDIUM, getLocale(context));
        } else if (value instanceof java.sql.Timestamp) {
            SimpleDateFormat dfmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT,
                    DateFormat.MEDIUM, getLocale(context));
            df = new SimpleDateFormat(dfmt.toPattern() + MILLISECOND_FORMAT);
        } else {
            df = DateFormat.getDateInstance(DateFormat.SHORT, getLocale(context));
        }
        result = df.format(value);
    } else if (value instanceof String[]) {
        result = StringUtils.join((String[]) value, ", ");
    }

    return result;
}

From source file:org.glom.web.server.ReportGenerator.java

/**
 * @param x/*from  w w w.j a v  a2  s.com*/
 * @param libglomLayoutItemField
 * @return
 */
private JRDesignTextField createFieldValueElement(final Position pos,
        final LayoutItemField libglomLayoutItemField) {
    final JRDesignTextField textField = new JRDesignTextField();

    // Make sure this field starts at the right of the previous field,
    // because JasperReports uses absolute positioning.
    textField.setY(pos.y);
    textField.setX(pos.x);
    textField.setWidth(width); // No data will be shown without this.

    // This only stretches vertically, but that is better than
    // nothing.
    textField.setStretchWithOverflow(true);
    textField.setHeight(height); // We must specify _some_ height.

    final JRDesignExpression expression = createFieldExpression(libglomLayoutItemField);
    textField.setExpression(expression);

    if (libglomLayoutItemField.getGlomType() == GlomFieldType.TYPE_NUMERIC) {
        // Numeric formatting:
        final Formatting formatting = libglomLayoutItemField.getFormattingUsed();
        final NumericFormat numericFormat = formatting.getNumericFormat();

        final DecimalFormat format = new DecimalFormat();
        format.setMaximumFractionDigits(numericFormat.getDecimalPlaces());
        format.setGroupingUsed(numericFormat.getUseThousandsSeparator());

        // TODO: Use numericFormat.get_currency_symbol(), possibly via format.setCurrency().
        textField.setPattern(format.toPattern());
    } else if (libglomLayoutItemField.getGlomType() == GlomFieldType.TYPE_DATE) {
        // Date formatting
        // TODO: Use a 4-digit-year short form, somehow.
        try // We use a try block because getDateInstance() is not guaranteed to return a SimpleDateFormat.
        {
            final SimpleDateFormat format = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT,
                    Locale.ROOT);

            textField.setPattern(format.toPattern());
        } catch (final Exception ex) {
            Log.info("ReportGenerator: The cast of SimpleDateFormat failed.");
        }
    } else if (libglomLayoutItemField.getGlomType() == GlomFieldType.TYPE_TIME) {
        // Time formatting
        try // We use a try block because getDateInstance() is not guaranteed to return a SimpleDateFormat.
        {
            final SimpleDateFormat format = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.SHORT,
                    Locale.ROOT);

            textField.setPattern(format.toPattern());
        } catch (final Exception ex) {
            Log.info("ReportGenerator: The cast of SimpleDateFormat failed.");
        }
    }

    return textField;
}

From source file:org.glom.web.server.SqlUtils.java

/**
 * @param dataItem/* w  w  w  . j a v  a 2  s.co m*/
 * @param field
 * @param rsIndex
 * @param rs
 * @param primaryKeyValue
 * @throws SQLException
 */
public static void fillDataItemFromResultSet(final DataItem dataItem, final LayoutItemField field,
        final int rsIndex, final ResultSet rs, final String documentID, final String tableName,
        final TypedDataItem primaryKeyValue) throws SQLException {

    switch (field.getGlomType()) {
    case TYPE_TEXT:
        final String text = rs.getString(rsIndex);
        dataItem.setText(text != null ? text : "");
        break;
    case TYPE_BOOLEAN:
        dataItem.setBoolean(rs.getBoolean(rsIndex));
        break;
    case TYPE_NUMERIC:
        dataItem.setNumber(rs.getDouble(rsIndex));
        break;
    case TYPE_DATE:
        final Date date = rs.getDate(rsIndex);
        if (date != null) {
            // TODO: Pass Date and Time types instead of converting to text here?
            // TODO: Use a 4-digit-year short form, somehow.
            final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ROOT);
            dataItem.setText(dateFormat.format(date));
        } else {
            dataItem.setText("");
        }
        break;
    case TYPE_TIME:
        final Time time = rs.getTime(rsIndex);
        if (time != null) {
            final DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.ROOT);
            dataItem.setText(timeFormat.format(time));
        } else {
            dataItem.setText("");
        }
        break;
    case TYPE_IMAGE:
        //We don't get the data here.
        //Instead we provide a way for the client to get the image separately.

        //This doesn't seem to work,
        //presumably because the base64 encoding is wrong:
        //final byte[] imageByteArray = rs.getBytes(rsIndex);
        //if (imageByteArray != null) {
        //   String base64 = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(imageByteArray);
        //   base64 = "data:image/png;base64," + base64;

        final String url = Utils.buildImageDataUrl(primaryKeyValue, documentID, tableName, field);
        dataItem.setImageDataUrl(url);
        break;
    case TYPE_INVALID:
    default:
        Log.warn(documentID, tableName, "Invalid LayoutItem Field type. Using empty string for value.");
        dataItem.setText("");
        break;
    }
}

From source file:org.apache.click.util.Format.java

/**
 * Return a formatted time string using the given date and the default
 * DateFormat.//from   ww  w .  ja va2  s.  co  m
 * <p/>
 * If the date is null this method will return the
 * {@link #getEmptyString()} value.
 *
 * @param date the date value to format
 * @return a formatted time string
 */
public String time(Date date) {
    if (date != null) {
        DateFormat format = DateFormat.getTimeInstance(DateFormat.DEFAULT, getLocale());

        return format.format(date);

    } else {
        return getEmptyString();
    }
}

From source file:DateFormatUtils.java

/**
 * <p>Gets a time formatter instance using the specified style, time
 * zone and locale.</p>/*from ww  w.  j a va  2 s .  co m*/
 * 
 * @param style  time style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted time
 * @param locale  optional locale, overrides system locale
 * @return a localized standard time formatter
 * @throws IllegalArgumentException if the Locale has no time
 *  pattern defined
 */
public static synchronized FastDateFormat getTimeInstance(int style, TimeZone timeZone, Locale locale) {
    Object key = new Integer(style);
    if (timeZone != null) {
        key = new Pair(key, timeZone);
    }
    if (locale != null) {
        key = new Pair(key, locale);
    }

    FastDateFormat format = (FastDateFormat) cTimeInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }

        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getTimeInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cTimeInstanceCache.put(key, format);

        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}

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

/**
 * Import lock box files.//from   w w  w .  j  a va2 s  .  c  o m
 *
 * @param now The current date.
 * @param isNowHoliday Indicate whether current is holiday
 * @return true if execution is successful; false to retry.
 * @throws BatchProcessingException If major error occurred.
 */
private boolean importFiles(Date now, boolean isNowHoliday) throws BatchProcessingException {
    StringBuilder procMessage = new StringBuilder();
    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);

    File inputDirectory = new File(inputDirectoryPath);
    if (!inputDirectory.exists() || !inputDirectory.isDirectory() || !inputDirectory.canRead()) {
        logger.error("Can not read folder: " + inputDirectory);

        procMessage.append("THE NETWORK IS DOWN! ");
        procMessage.append(CRLF);
        procMessage.append("Network Services not Available for Service Credit. Cannot access the ");
        procMessage.append(inputDirectoryPath);
        procMessage.append(" network folder. Please ask the Help Desk to investigate. ");
        procMessage.append("SERVICE CREDIT IS SHUT DOWN UNTIL THIS ERROR IS FIXED! ");
        notifyByEmail(procMessage.toString(), "SERVICE CREDIT BATCH CANNOT ACCESS NETWORK", "Testing Network");
        auditError("SERVICE CREDIT BATCH CANNOT ACCESS NETWORK", procMessage.toString());
        return false;
    }

    // Filter the input lockbox files
    final String regex = wildCardInput.replace("?", ".?").replace("*", ".*?");
    File[] inputFiles = inputDirectory.listFiles(new FileFilter() {
        @Override
        public boolean accept(File inputFile) {
            if (inputFile.getName().matches(regex)) {
                if (inputFile.isFile() && inputFile.canRead() && inputFile.canWrite()) {
                    return true;
                }
                logger.warn("Does not have read/write permission to file: " + inputFile);
            }
            return false;
        }
    });

    if (inputFiles.length == 0) {
        if (!isNowHoliday && Boolean.TRUE != todayAuditBatch.getFileReceived()) {
            logger.error("No files arrived today in: " + inputDirectory);

            procMessage.append("Today's Lockbox Bank File has not arrived. Please notify Production Control"
                    + " and BSG that the data file is not in the ");
            procMessage.append(inputDirectoryPath);
            procMessage.append(" network share. The nightly batch process is scheduled to run at ");
            procMessage.append(DateFormat.getTimeInstance(DateFormat.LONG, Locale.US).format(now));
            procMessage.append(" and today's import should run before that time. ");
            notifyByEmail(procMessage.toString(), "SERVICE CREDIT LOCKBOX FILE IS LATE!", "ERROR");
            auditError("SERVICE CREDIT LOCKBOX FILE IS LATE!", procMessage.toString());
            return false;
        }
        return true;
    }

    // Mark file arrived
    if (Boolean.TRUE != todayAuditBatch.getFileReceived()) {
        todayAuditBatch.setFileReceived(true);
        try {
            todayAuditBatch = mergeEntity(todayAuditBatch);
        } catch (PersistenceException pe) {
            throw new BatchProcessingException(
                    "Database error while updating audit batch log when importing files", pe);
        }
    }

    // Import files
    logger.info("Start importing files in: " + inputDirectory);
    for (File inputFile : inputFiles) {
        if (!inputFile.exists() || !inputFile.isFile() || !inputFile.canRead()) {
            // Just make sure
            logger.warn("Lockbox file is not a readable file: " + inputFile);
            continue;
        }

        importFile(procMessage, inputFile);
    }
    logger.info("End importing files in: " + inputDirectory);

    return true;
}

From source file:org.libreplan.web.common.Util.java

/**
 * Format specific <code>time</code> using the {@link DateFormat#SHORT} format and showing only the time.
 *///from   www. j av a 2s. co  m
public static String formatTime(Date time) {
    return time == null ? "" : DateFormat.getTimeInstance(DateFormat.SHORT, Locales.getCurrent()).format(time);
}

From source file:com.rogchen.common.xml.UtilDateTime.java

/**
 * Returns an initialized DateFormat object.
 *
 * @param timeFormat optional format string
 * @param tz/*  w  w w  .j  av  a2  s .c  om*/
 * @param locale can be null if timeFormat is not null
 * @return DateFormat object
 */
public static DateFormat toTimeFormat(String timeFormat, TimeZone tz, Locale locale) {
    DateFormat df = null;
    if (timeFormat == null) {
        df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
    } else {
        df = new SimpleDateFormat(timeFormat);
    }
    df.setTimeZone(tz);
    return df;
}

From source file:org.sakaiproject.cheftool.VelocityPortletPaneledAction.java

/**
 ** Return a String array containing the "h", "m", "a", or "H" characters (corresponding to hour, minute, am/pm, or 24-hour)
 ** in the locale specific order/*from   ww w.  j ava  2 s  .  co m*/
 **/
public String[] getTimeFormatString() {
    SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.SHORT, rb.getLocale());
    String format = sdf.toPattern();

    Set<String> formatSet = new LinkedHashSet<String>();
    char curChar;
    char lastChar = 0;
    for (int i = 0; i < format.length(); i++) {
        curChar = format.charAt(i);
        if ((curChar == 'h' || curChar == 'm' || curChar == 'a' || curChar == 'H') && curChar != lastChar) {
            formatSet.add(String.valueOf(curChar));
            lastChar = curChar;
        }
    }

    String[] formatArray = formatSet.toArray(new String[formatSet.size()]);
    if (formatArray.length != DEFAULT_TIME_FORMAT_ARRAY.length
            && formatArray.length != DEFAULT_TIME_FORMAT_ARRAY.length - 1) {
        M_log.warn("Unknown time format string (using default): " + format);
        return DEFAULT_TIME_FORMAT_ARRAY.clone();
    } else {
        return formatArray;
    }
}

From source file:org.gvnix.web.screen.roo.addon.SeleniumServicesImpl.java

/**
 * Get test value for a field.//ww  w . java  2 s  .c om
 * 
 * @param field Field to auto generate a value
 * @param random Should be the initialized value generated randomly ?
 * @return Field test value
 */
private String convertToInitializer(FieldMetadata field, boolean random) {

    String initializer = " ";

    short index = 1;
    if (random) {
        index = (short) RANDOM_GENERATOR.nextInt();
    }

    AnnotationMetadata min = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(),
            new JavaType("javax.validation.constraints.Min"));
    if (min != null) {
        AnnotationAttributeValue<?> value = min.getAttribute(new JavaSymbolName("value"));
        if (value != null) {
            index = Short.valueOf(value.getValue().toString());
        }
    }
    if (field.getFieldName().getSymbolName().contains("email")
            || field.getFieldName().getSymbolName().contains("Email")) {
        initializer = "some@email.com";
    } else if (field.getFieldType().equals(JavaType.STRING)) {
        initializer = "some" + field.getFieldName().getSymbolNameCapitalisedFirstLetter() + index;
    } else if (field.getFieldType().equals(new JavaType(Date.class.getName()))
            || field.getFieldType().equals(new JavaType(Calendar.class.getName()))) {
        Calendar cal = Calendar.getInstance();
        AnnotationMetadata dateTimeFormat = null;
        String style = null;
        if (null != (dateTimeFormat = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(),
                new JavaType("org.springframework.format.annotation.DateTimeFormat")))) {
            AnnotationAttributeValue<?> value = dateTimeFormat.getAttribute(new JavaSymbolName("style"));
            if (value != null) {
                style = value.getValue().toString();
            }
        }
        if (null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(),
                new JavaType("javax.validation.constraints.Past"))) {
            cal.add(Calendar.YEAR, -1);
            cal.add(Calendar.MONTH, -1);
            cal.add(Calendar.DAY_OF_MONTH, -1);
        } else if (null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(),
                new JavaType("javax.validation.constraints.Future"))) {
            cal.add(Calendar.YEAR, +1);
            cal.add(Calendar.MONTH, +1);
            cal.add(Calendar.DAY_OF_MONTH, +1);
        }
        if (style != null) {
            if (style.startsWith("-")) {
                initializer = ((SimpleDateFormat) DateFormat
                        .getTimeInstance(DateTime.parseDateFormat(style.charAt(1)), Locale.getDefault()))
                                .format(cal.getTime());
            } else if (style.endsWith("-")) {
                initializer = ((SimpleDateFormat) DateFormat
                        .getDateInstance(DateTime.parseDateFormat(style.charAt(0)), Locale.getDefault()))
                                .format(cal.getTime());
            } else {
                initializer = ((SimpleDateFormat) DateFormat.getDateTimeInstance(
                        DateTime.parseDateFormat(style.charAt(0)), DateTime.parseDateFormat(style.charAt(1)),
                        Locale.getDefault())).format(cal.getTime());
            }
        } else {
            initializer = ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()))
                    .format(cal.getTime());
        }

    } else if (field.getFieldType().equals(JavaType.BOOLEAN_OBJECT)
            || field.getFieldType().equals(JavaType.BOOLEAN_PRIMITIVE)) {
        initializer = Boolean.FALSE.toString();
    } else if (field.getFieldType().equals(JavaType.INT_OBJECT)
            || field.getFieldType().equals(JavaType.INT_PRIMITIVE)) {
        initializer = Integer.valueOf(index).toString();
    } else if (field.getFieldType().equals(JavaType.DOUBLE_OBJECT)
            || field.getFieldType().equals(JavaType.DOUBLE_PRIMITIVE)) {
        initializer = Double.valueOf(index).toString();
    } else if (field.getFieldType().equals(JavaType.FLOAT_OBJECT)
            || field.getFieldType().equals(JavaType.FLOAT_PRIMITIVE)) {
        initializer = Float.valueOf(index).toString();
    } else if (field.getFieldType().equals(JavaType.LONG_OBJECT)
            || field.getFieldType().equals(JavaType.LONG_PRIMITIVE)) {
        initializer = Long.valueOf(index).toString();
    } else if (field.getFieldType().equals(JavaType.SHORT_OBJECT)
            || field.getFieldType().equals(JavaType.SHORT_PRIMITIVE)) {
        initializer = Short.valueOf(index).toString();
    } else if (field.getFieldType().equals(new JavaType("java.math.BigDecimal"))) {
        initializer = BigDecimal.valueOf(index).toString();
    }
    return initializer;
}