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.toobsframework.transformpipeline.xslExtentions.DateHelper.java

private static DateFormat createTimeFormatter(String languageCode) {
    DateFormat formatter = null;//ww w. j  a va  2 s  . com

    if ((languageCode != null) && !("".equalsIgnoreCase(languageCode.trim()))) {
        languageCode = languageCode.trim();

        Locale locale = new Locale(languageCode.substring(2, 4).toLowerCase(), languageCode.substring(0, 2));
        formatter = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
    } else {
        formatter = DateFormat.getTimeInstance(DateFormat.SHORT);
    }

    return formatter;
}

From source file:org.jivesoftware.util.JiveGlobals.java

/**
 * Formats a Date object to return a time using the global locale.
 *
 * @param date the Date to format./*from ww  w. j a  v a2 s  .c om*/
 * @return a String representing the time.
 */
public static String formatTime(Date date) {
    if (timeFormat == null) {
        if (properties != null) {
            timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, getLocale());
            timeFormat.setTimeZone(getTimeZone());
        } else {
            DateFormat instance = DateFormat.getTimeInstance(DateFormat.SHORT, getLocale());
            instance.setTimeZone(getTimeZone());
            return instance.format(date);
        }
    }
    return timeFormat.format(date);
}

From source file:org.olat.core.util.Formatter.java

License:asdf

/**
 * formats the given time period so it is friendly to read
 * /*from   www.j av  a2  s  .  co m*/
 * @param d the date
 * @return a String with the formatted time
 */
public String formatTimeShort(Date d) {
    DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
    df.setLenient(false);
    String da = df.format(d);
    return da;
}

From source file:com.adamkruger.myipaddressinfo.IPAddressInfoFragment.java

private void updateViewState() {
    View view = getView();/*from   w w  w  .  j a  v a2  s .c  o m*/
    if (view != null) {
        ((TextView) view.findViewById(R.id.ipValue)).setText(mIPAddress);
        ((TextView) view.findViewById(R.id.ispValue)).setText(mISP);
        ((TextView) view.findViewById(R.id.countryValue)).setText(mCountry);
        ((TextView) view.findViewById(R.id.cityValue)).setText(mCity);
        ((TextView) view.findViewById(R.id.regionValue)).setText(mRegion);
        ((TextView) view.findViewById(R.id.coordinatesValue)).setText(mLatLong.length() == 0 ? ""
                : Html.fromHtml(
                        String.format("<a href=\"%s\">%s</a>", mapLink(mLatLong, mIPAddress), mLatLong)));

        if (mLastUpdateTime != null) {
            TextView lastUpdateStatus = (TextView) view.findViewById(R.id.lastUpdateStatus);
            if (mLastUpdateTimedOut) {
                lastUpdateStatus
                        .setText(String.format(getResources().getString(R.string.last_update_status_timeout),
                                mLastUpdateElapsedTimeMs / 1000));
                lastUpdateStatus.setTextColor(getResources().getColor(R.color.error_color));
            } else if (mLastUpdateSucceeded) {
                lastUpdateStatus
                        .setText(String.format(getResources().getString(R.string.last_update_status_success),
                                mLastUpdateElapsedTimeMs));
                if (mLastUpdateElapsedTimeMs < 2000) {
                    lastUpdateStatus.setTextColor(getResources().getColor(R.color.success_color));
                } else {
                    lastUpdateStatus.setTextColor(getResources().getColor(R.color.warning_color));
                }
            } else {
                lastUpdateStatus.setText(String.format(
                        getResources().getString(R.string.last_update_status_fail), mLastUpdateElapsedTimeMs));
                lastUpdateStatus.setTextColor(getResources().getColor(R.color.error_color));
            }

            TextView lastUpdateTime = (TextView) view.findViewById(R.id.lastUpdateTime);
            lastUpdateTime.setText(
                    String.format(getResources().getString(R.string.last_update_time), mLastUpdateTime));
            String currentTime = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault())
                    .format(new Date());
            if (currentTime.equals(mLastUpdateTime)) {
                lastUpdateTime.setTextColor(mDefaultLastUpdateTimeColor);
            } else {
                lastUpdateTime.setTextColor(getResources().getColor(R.color.warning_color));
            }
        }
    }
}

From source file:org.apache.ddlutils.platform.SqlBuilder.java

/**
 * Sets the locale that is used for number and date formatting
 * (when printing default values and in generates insert/update/delete
 * statements)./*w w  w  .ja  v  a  2  s .  c o  m*/
 *
 * @param localeStr The new locale or <code>null</code> if default formatting
 *                  should be used; Format is "language[_country[_variant]]"
 */
public void setValueLocale(String localeStr) {
    if (localeStr != null) {
        int sepPos = localeStr.indexOf('_');
        String language = null;
        String country = null;
        String variant = null;

        if (sepPos > 0) {
            language = localeStr.substring(0, sepPos);
            country = localeStr.substring(sepPos + 1);
            sepPos = country.indexOf('_');
            if (sepPos > 0) {
                variant = country.substring(sepPos + 1);
                country = country.substring(0, sepPos);
            }
        } else {
            language = localeStr;
        }
        if (language != null) {
            Locale locale = null;

            if (variant != null) {
                locale = new Locale(language, country, variant);
            } else if (country != null) {
                locale = new Locale(language, country);
            } else {
                locale = new Locale(language);
            }

            _valueLocale = localeStr;
            setValueDateFormat(DateFormat.getDateInstance(DateFormat.SHORT, locale));
            setValueTimeFormat(DateFormat.getTimeInstance(DateFormat.SHORT, locale));
            setValueNumberFormat(NumberFormat.getNumberInstance(locale));
            return;
        }
    }
    _valueLocale = null;
    setValueDateFormat(null);
    setValueTimeFormat(null);
    setValueNumberFormat(null);
}

From source file:org.exoplatform.outlook.social.OutlookMessageActivity.java

/**
 * {@inheritDoc}//from ww w. jav  a 2s . c o  m
 */
@Override
public String getSummary(Node node) {
    try {
        if (node.isNodeType(OutlookService.MESSAGE_NODETYPE)) {
            String fromEmail = node.getProperty("mso:fromEmail").getString();
            String fromName = node.getProperty("mso:fromName").getString();
            Date time = node.getProperty("mso:created").getDate().getTime();

            Locale userLocale = null;
            RequestContext context = RequestContext.getCurrentInstance();
            OrganizationService orgService = getApplicationComponent(OrganizationService.class);
            try {
                UserProfile userProfile = orgService.getUserProfileHandler()
                        .findUserProfileByName(context.getRemoteUser());
                if (userProfile != null) {
                    String lang = userProfile.getUserInfoMap().get(Constants.USER_LANGUAGE);
                    if (lang != null) {
                        userLocale = LocaleContextInfo.getLocale(lang);
                    }
                } else if (LOG.isDebugEnabled()) {
                    LOG.debug("User profile not found for " + context.getRemoteUser());
                }
            } catch (Exception e) {
                LOG.warn("Error getting user profile for " + context.getRemoteUser(), e);
            }

            if (userLocale == null) {
                // try find locale from user request
                if (PortletRequestContext.class.isAssignableFrom(context.getClass())) {
                    userLocale = ((PortalRequestContext) PortletRequestContext.class.cast(context)
                            .getParentAppRequestContext()).getRequest().getLocale();
                } else if (PortalRequestContext.class.isAssignableFrom(context.getClass())) {
                    userLocale = PortalRequestContext.class.cast(context).getRequest().getLocale();
                }
                if (userLocale == null) {
                    // it's server locale in most cases
                    userLocale = context.getLocale();
                    if (userLocale == null) {
                        userLocale = Locale.ENGLISH;
                    }
                }
            }

            DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, userLocale);
            DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, userLocale);

            ResourceBundle res = context.getApplicationResourceBundle();

            StringBuilder fromLine = new StringBuilder();
            fromLine.append(fromName);
            fromLine.append('<');
            fromLine.append(fromEmail);
            fromLine.append('>');

            StringBuilder summary = new StringBuilder();
            summary.append(res.getString("Outlook.activity.from"));
            summary.append(": <a href='mailto:");
            summary.append(fromEmail);
            summary.append("' target='_top'>");
            summary.append(ContentReader.simpleEscapeHtml(fromLine.toString()));
            summary.append("</a> ");
            summary.append(res.getString("Outlook.activity.on"));
            summary.append(' ');
            summary.append(dateFormat.format(time));
            summary.append(' ');
            summary.append(res.getString("Outlook.activity.at"));
            summary.append(' ');
            summary.append(timeFormat.format(time));

            return summary.toString();
        }
    } catch (RepositoryException e) {
        LOG.warn("Error generating info for Outlook message activity node " + node, e);
    }

    return super.getSummary(node);
}

From source file:org.jumpmind.db.platform.AbstractDdlBuilder.java

/**
 * Sets the locale that is used for number and date formatting (when
 * printing default values and in generates insert/update/delete
 * statements).//from  ww w . jav  a  2  s .  co  m
 *
 * @param localeStr
 *            The new locale or <code>null</code> if default formatting
 *            should be used; Format is "language[_country[_variant]]"
 */
public void setValueLocale(String localeStr) {
    if (localeStr != null) {
        int sepPos = localeStr.indexOf('_');
        String language = null;
        String country = null;
        String variant = null;

        if (sepPos > 0) {
            language = localeStr.substring(0, sepPos);
            country = localeStr.substring(sepPos + 1);
            sepPos = country.indexOf('_');
            if (sepPos > 0) {
                variant = country.substring(sepPos + 1);
                country = country.substring(0, sepPos);
            }
        } else {
            language = localeStr;
        }
        if (language != null) {
            Locale locale = null;

            if (variant != null) {
                locale = new Locale(language, country, variant);
            } else if (country != null) {
                locale = new Locale(language, country);
            } else {
                locale = new Locale(language);
            }

            valueLocale = localeStr;
            setValueDateFormat(DateFormat.getDateInstance(DateFormat.SHORT, locale));
            setValueTimeFormat(DateFormat.getTimeInstance(DateFormat.SHORT, locale));
            setValueNumberFormat(NumberFormat.getNumberInstance(locale));
            return;
        }
    }
    valueLocale = null;
    setValueDateFormat(null);
    setValueTimeFormat(null);
    setValueNumberFormat(null);
}

From source file:com.brq.wallet.activity.export.BackupToPdfActivity.java

private String getExportFileName(long exportTime) {
    Date exportDate = new Date(exportTime);
    Locale locale = getResources().getConfiguration().locale;
    String hourString = DateFormat.getDateInstance(DateFormat.SHORT, locale).format(exportDate);
    hourString = replaceInvalidFileNameChars(hourString);
    String dateString = DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(exportDate);
    dateString = replaceInvalidFileNameChars(dateString);
    return FILE_NAME_PREFIX + '-' + hourString + '-' + dateString + ".pdf";
}

From source file:com.opensymphony.xwork2.conversion.impl.XWorkBasicConverter.java

private Object doConvertToDate(Map<String, Object> context, Object value, Class toType) {
    Date result = null;/* ww  w  .  ja va 2s.  c o  m*/

    if (value instanceof String && value != null && ((String) value).length() > 0) {
        String sa = (String) value;
        Locale locale = getLocale(context);

        DateFormat df = null;
        if (java.sql.Time.class == toType) {
            df = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
        } else if (java.sql.Timestamp.class == toType) {
            Date check = null;
            SimpleDateFormat dtfmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.SHORT,
                    DateFormat.MEDIUM, locale);
            SimpleDateFormat fullfmt = new SimpleDateFormat(dtfmt.toPattern() + MILLISECOND_FORMAT, locale);

            SimpleDateFormat dfmt = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, locale);

            SimpleDateFormat[] fmts = { fullfmt, dtfmt, dfmt };
            for (SimpleDateFormat fmt : fmts) {
                try {
                    check = fmt.parse(sa);
                    df = fmt;
                    if (check != null) {
                        break;
                    }
                } catch (ParseException ignore) {
                }
            }
        } else if (java.util.Date.class == toType) {
            Date check = null;
            DateFormat[] dfs = getDateFormats(locale);
            for (DateFormat df1 : dfs) {
                try {
                    check = df1.parse(sa);
                    df = df1;
                    if (check != null) {
                        break;
                    }
                } catch (ParseException ignore) {
                }
            }
        }
        //final fallback for dates without time
        if (df == null) {
            df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        }
        try {
            df.setLenient(false); // let's use strict parsing (XW-341)
            result = df.parse(sa);
            if (!(Date.class == toType)) {
                try {
                    Constructor constructor = toType.getConstructor(new Class[] { long.class });
                    return constructor.newInstance(new Object[] { Long.valueOf(result.getTime()) });
                } catch (Exception e) {
                    throw new XWorkException(
                            "Couldn't create class " + toType + " using default (long) constructor", e);
                }
            }
        } catch (ParseException e) {
            throw new XWorkException("Could not parse date", e);
        }
    } else if (Date.class.isAssignableFrom(value.getClass())) {
        result = (Date) value;
    }
    return result;
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java

private TickUnits createTickUnits(Locale locale, TimeZone zone) {
    TickUnits units = new TickUnits();

    // date formatters
    DateFormat f1 = new SimpleDateFormat("HH:mm:ss.SSS", locale);
    DateFormat f2 = new SimpleDateFormat("HH:mm:ss", locale);
    DateFormat f3 = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
    DateFormat f4 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
    DateFormat f5 = new SimpleDateFormat("d-MMM", locale);
    DateFormat f6 = new SimpleDateFormat("MMM-yyyy", locale);
    DateFormat f7 = new SimpleDateFormat("yyyy", locale);

    // NOTE: timezone not needed on date formatters because dates have already been converted
    // to the appropriate timezone by the respective RegularTimePeriod (Minute, Hour, Day, etc)
    // see:/*from  w w w  .  j  ava2s  .com*/
    //   http://www.jfree.org/jfreechart/api/gjdoc/org/jfree/data/time/Hour.html#Hour:Date:TimeZone
    //
    // If you do use a timezone on the formatters and the Jive TimeZone has been set to something
    // other than the system timezone, time specific charts will show incorrect values.
    /*
    f1.setTimeZone(zone);
    f2.setTimeZone(zone);
    f3.setTimeZone(zone);
    f4.setTimeZone(zone);
    f5.setTimeZone(zone);
    f6.setTimeZone(zone);
    f7.setTimeZone(zone);
    */

    // milliseconds
    units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 1, f1));
    units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 5, DateTickUnit.MILLISECOND, 1, f1));
    units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 10, DateTickUnit.MILLISECOND, 1, f1));
    units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 25, DateTickUnit.MILLISECOND, 5, f1));
    units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 50, DateTickUnit.MILLISECOND, 10, f1));
    units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 100, DateTickUnit.MILLISECOND, 10, f1));
    units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 250, DateTickUnit.MILLISECOND, 10, f1));
    units.add(new DateTickUnit(DateTickUnit.MILLISECOND, 500, DateTickUnit.MILLISECOND, 50, f1));

    // seconds
    units.add(new DateTickUnit(DateTickUnit.SECOND, 1, DateTickUnit.MILLISECOND, 50, f2));
    units.add(new DateTickUnit(DateTickUnit.SECOND, 5, DateTickUnit.SECOND, 1, f2));
    units.add(new DateTickUnit(DateTickUnit.SECOND, 10, DateTickUnit.SECOND, 1, f2));
    units.add(new DateTickUnit(DateTickUnit.SECOND, 30, DateTickUnit.SECOND, 5, f2));

    // minutes
    units.add(new DateTickUnit(DateTickUnit.MINUTE, 1, DateTickUnit.SECOND, 5, f3));
    units.add(new DateTickUnit(DateTickUnit.MINUTE, 2, DateTickUnit.SECOND, 10, f3));
    units.add(new DateTickUnit(DateTickUnit.MINUTE, 5, DateTickUnit.MINUTE, 1, f3));
    units.add(new DateTickUnit(DateTickUnit.MINUTE, 10, DateTickUnit.MINUTE, 1, f3));
    units.add(new DateTickUnit(DateTickUnit.MINUTE, 15, DateTickUnit.MINUTE, 5, f3));
    units.add(new DateTickUnit(DateTickUnit.MINUTE, 20, DateTickUnit.MINUTE, 5, f3));
    units.add(new DateTickUnit(DateTickUnit.MINUTE, 30, DateTickUnit.MINUTE, 5, f3));

    // hours
    units.add(new DateTickUnit(DateTickUnit.HOUR, 1, DateTickUnit.MINUTE, 5, f3));
    units.add(new DateTickUnit(DateTickUnit.HOUR, 2, DateTickUnit.MINUTE, 10, f3));
    units.add(new DateTickUnit(DateTickUnit.HOUR, 4, DateTickUnit.MINUTE, 30, f3));
    units.add(new DateTickUnit(DateTickUnit.HOUR, 6, DateTickUnit.HOUR, 1, f3));
    units.add(new DateTickUnit(DateTickUnit.HOUR, 12, DateTickUnit.HOUR, 1, f4));

    // days
    units.add(new DateTickUnit(DateTickUnit.DAY, 1, DateTickUnit.HOUR, 1, f5));
    units.add(new DateTickUnit(DateTickUnit.DAY, 2, DateTickUnit.HOUR, 1, f5));
    units.add(new DateTickUnit(DateTickUnit.DAY, 7, DateTickUnit.DAY, 1, f5));
    units.add(new DateTickUnit(DateTickUnit.DAY, 15, DateTickUnit.DAY, 1, f5));

    // months
    units.add(new DateTickUnit(DateTickUnit.MONTH, 1, DateTickUnit.DAY, 1, f6));
    units.add(new DateTickUnit(DateTickUnit.MONTH, 2, DateTickUnit.DAY, 1, f6));
    units.add(new DateTickUnit(DateTickUnit.MONTH, 3, DateTickUnit.MONTH, 1, f6));
    units.add(new DateTickUnit(DateTickUnit.MONTH, 4, DateTickUnit.MONTH, 1, f6));
    units.add(new DateTickUnit(DateTickUnit.MONTH, 6, DateTickUnit.MONTH, 1, f6));

    // years
    units.add(new DateTickUnit(DateTickUnit.YEAR, 1, DateTickUnit.MONTH, 1, f7));
    units.add(new DateTickUnit(DateTickUnit.YEAR, 2, DateTickUnit.MONTH, 3, f7));
    units.add(new DateTickUnit(DateTickUnit.YEAR, 5, DateTickUnit.YEAR, 1, f7));
    units.add(new DateTickUnit(DateTickUnit.YEAR, 10, DateTickUnit.YEAR, 1, f7));
    units.add(new DateTickUnit(DateTickUnit.YEAR, 25, DateTickUnit.YEAR, 5, f7));
    units.add(new DateTickUnit(DateTickUnit.YEAR, 50, DateTickUnit.YEAR, 10, f7));
    units.add(new DateTickUnit(DateTickUnit.YEAR, 100, DateTickUnit.YEAR, 20, f7));

    return units;
}