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.openvpms.web.resource.i18n.format.DateFormatter.java

/**
 * Returns a time format./*from  w ww . ja  v a2  s. c om*/
 * <p/>
 * This will use the <em>time.format.edit</em> and <em>time.format.view</em> properties if specified in
 * <em>messages.properties</em>, else it will fall back to those provided by the locale.
 *
 * @param edit if {@code true} return a format for editing otherwise
 *             return a format for viewing dates
 * @return a date format
 */
public static DateFormat getTimeFormat(boolean edit) {
    DateFormat format;
    Locale locale = Messages.getLocale();
    String pattern = (edit) ? TIME_EDIT_PATTERN : TIME_VIEW_PATTERN;
    if (pattern == null) {
        if (edit) {
            // specify SHORT style when parsing, so that 2 digit years
            // are handled correctly
            format = DateFormat.getTimeInstance(DateFormat.SHORT, locale);
        } else {
            format = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
        }
    } else {
        format = new SimpleDateFormat(pattern, locale);
    }
    return format;
}

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

/**
 * @param time//  w ww.ja v a 2s .  c o m
 * @param locale
 * @return formatted time
 */
public static String formatLocaleTime(long time, Locale locale) {
    if (time == -1)
        return "-";
    return DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(new Date(time));
}

From source file:DateUtil.java

/**
 * Parses given string according to specified locale and time style
 *
 * @param source    Source string to parse time from
 * @param locale    Locale to use for parsing time
 * @param timeStyle Time style/*w  w  w  .j  ava2 s .  co m*/
 * @return Time object corresponding to representation given in source string
 * @throws ParseException if given string could not be properly parsed according to given locale and style
 * @see java.text.DateFormat
 */
public static Date parseTime(String source, Locale locale, int timeStyle) throws ParseException {
    DateFormat formatter = DateFormat.getTimeInstance(timeStyle, locale);
    return formatter.parse(source);
}

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

/**
 * //from ww w  . ja v a 2s .com
 * @param time
 * @param locale
 * @return
 */
public static String formatLocaleTime(Date time, Locale locale) {
    if (time == null)
        return "-";
    return DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(time);
}

From source file:org.openvpms.web.resource.i18n.format.DateFormatter.java

/**
 * Returns the time format for the specified style and current locale.
 *
 * @param style the style//from   ww w  .  ja  v a2s.  c om
 * @return the corresponding time format
 */
public static DateFormat getTimeFormat(int style) {
    return DateFormat.getTimeInstance(style, Messages.getLocale());
}

From source file:jp.furplag.util.time.DateTimeUtils.java

/**
 * create a localized pattern string describing the datetime format from a two character style pattern.
 * <p>//from w  w  w  .  j a  v a  2  s .  c  o m
 * The first character of {@code style} is the date style, and the second character is the time style.
 * </p>
 *
 * @param style specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be omitted by specifying a style character '-'.
 * @param locale
 * @return
 */
public static String getPattern(final String style, final Object locale) {
    FormatStyle[] styles = FormatStyle.forStyles(style);
    StringBuilder sb = new StringBuilder();
    if (styles[0].is())
        sb.append(((SimpleDateFormat) DateFormat.getDateInstance(styles[0].style,
                Localizer.getAvailableLocale(locale))).toPattern());
    if (styles[0].is() && styles[1].is())
        sb.append(" ");
    if (styles[1].is())
        sb.append(((SimpleDateFormat) DateFormat.getTimeInstance(styles[1].style,
                Localizer.getAvailableLocale(locale))).toPattern());

    return sb.toString();
}

From source file:com.carser.viamais.entity.Transaction.java

public void generateReceipt(final OutputStream os, final String template)
        throws IOException, DocumentException {
    reader = new PdfReader(this.getClass().getResourceAsStream("/receipts/" + template));
    stamper = new PdfStamper(reader, os);
    form = stamper.getAcroFields();//from   w  ww.  ja v a2s  . co  m
    brazilLocale = new Locale("pt", "BR");
    formatter = NumberFormat.getCurrencyInstance(brazilLocale);
    // Customer data
    Customer customer = getCustomer();
    form.setField("CUSTOMER_NAME", customer.getName().toUpperCase());
    form.setField("CUSTOMER_CPF", StringUtil.formatCPF(customer.getCpf()));
    form.setField("CUSTOMER_RG", customer.getRg().toUpperCase());
    // Addres data
    Address address = customer.getAddresses().get(0);
    StringBuilder addressDescription = new StringBuilder();
    addressDescription.append(address.getStreet());
    addressDescription.append(", " + address.getNumber());
    if (address.getComplement() != null) {
        addressDescription.append(", " + address.getComplement());
    }
    form.setField("CUSTOMER_ADDRESS", addressDescription.toString().toUpperCase());
    form.setField("CUSTOMER_DISTRICT", address.getDistrict().toUpperCase());
    form.setField("CUSTOMER_CEP", address.getCep());
    form.setField("CUSTOMER_CITY", address.getCity().toUpperCase());
    form.setField("CUSTOMER_STATE", address.getState().toUpperCase());
    List<Phone> phones = customer.getPhones();
    for (Phone phone : phones) {
        String phoneNumber = StringUtil.formatPhone(Long.valueOf(phone.getPrefix() + "" + phone.getNumber()));
        switch (phone.getType()) {
        case "Celular":
            form.setField("CUSTOMER_CELLPHONE", phoneNumber);
            break;
        case "Residencial":
            form.setField("CUSTOMER_PHONE", phoneNumber);
            break;
        case "Comercial":
            form.setField("CUSTOMER_COMPHONE", phoneNumber);
            break;
        default:
            break;
        }
    }
    // Car data
    Car car = getCar();
    form.setField("CAR_MANUFACTURER", car.getModel().getManufacturer().getName().toUpperCase());
    form.setField("CAR_MODEL", car.getModel().getName().toUpperCase());
    form.setField("CAR_YEAR", car.getYearOfManufacture() + "/" + car.getYearOfModel());
    form.setField("CAR_COLOR", car.getColor().toUpperCase());
    form.setField("CAR_PLATE", car.getLicensePlate().toUpperCase());
    form.setField("CAR_CHASSI", car.getChassi().toUpperCase());
    form.setField("CAR_RENAVAM", car.getRenavam().toUpperCase());
    // Transaction data
    form.setField("CAR_DEPOSIT",
            formatter.format(getDeposit()) + " (" + StringUtil.formatCurrency(getDeposit()) + ")");
    DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.LONG, brazilLocale);
    form.setField("CAR_VALUE",
            formatter.format(getPrice()) + " (" + StringUtil.formatCurrency(getPrice()) + ")");
    form.setField("DATE", dateFormatter.format(new Date()));
    DateFormat deliveryDateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, brazilLocale);
    DateFormat deliveryTimeFormatter = DateFormat.getTimeInstance(DateFormat.SHORT, brazilLocale);
    if (getDeliveryDate() != null) {
        form.setField("DELIVERY_DATE", deliveryDateFormatter.format(getDeliveryDate()) + " "
                + deliveryTimeFormatter.format(getDeliveryDate()));
    }
    if (getKm() != null) {
        form.setField("DELIVERY_KM", getKm().toString());
    }

}

From source file:fr.free.coup2lapan.ActualStateActivity.java

public BatteryStat getBatteryStatus() {

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent status = this.registerReceiver(null, ifilter);

    BatteryStat batterystat = new BatteryStat(status.getIntExtra(BatteryManager.EXTRA_LEVEL, 0),
            status.getIntExtra(BatteryManager.EXTRA_SCALE, 0),
            status.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0),
            status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0),
            status.getIntExtra(BatteryManager.EXTRA_STATUS, 0),
            status.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0),
            status.getIntExtra(BatteryManager.EXTRA_HEALTH, 0),
            status.getExtras().getBoolean(BatteryManager.EXTRA_PRESENT) ? 1 : 0,
            DateFormat.getDateInstance(2, localeFR).format(new Date())
                    + DateFormat.getTimeInstance(2, localeFR).format(new Date()),
            status.getExtras().getString(BatteryManager.EXTRA_TECHNOLOGY));

    return batterystat;
}

From source file:org.sakaiproject.calendar.impl.readers.IcalendarReader.java

public void importStreamFromDelimitedFile(InputStream stream, ReaderImportRowHandler handler)
        throws ImportException//, IOException, ParserException
{

    try {/*from w w w  .  j a va 2s.  c  o  m*/

        ColumnHeader columnDescriptionArray[] = null;
        String descriptionColumns[] = { "Summary", "Description", "Start Date", "Start Time", "Duration",
                "Location" };

        int lineNumber = 1;
        String durationformat = "";
        String requireValues = "";

        // column map stuff
        trimLeadingTrailingQuotes(descriptionColumns);
        columnDescriptionArray = buildColumnDescriptionArray(descriptionColumns);

        // enable "relaxed parsing"; read file using LF instead of CRLF
        CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
        CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
        CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true);
        CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);

        CalendarBuilder builder = new CalendarBuilder();
        net.fortuna.ical4j.model.Calendar calendar = builder.build(stream);

        for (Iterator i = calendar.getComponents("VEVENT").iterator(); i.hasNext();) {
            Component component = (Component) i.next();

            // Find event duration
            DateProperty dtstartdate;
            DateProperty dtenddate;
            if (component instanceof VEvent) {
                VEvent vEvent = (VEvent) component;
                dtstartdate = vEvent.getStartDate();
                dtenddate = vEvent.getEndDate(true);
            } else {
                dtstartdate = (DateProperty) component.getProperty("DTSTART");
                dtenddate = (DateProperty) component.getProperty("DTEND");
            }

            if (component.getProperty("SUMMARY") == null) {
                M_log.warn("IcalendarReader: SUMMARY is required; event not imported");
                continue;
            }
            String summary = component.getProperty("SUMMARY").getValue();

            if (component.getProperty("RRULE") != null) {
                M_log.warn("IcalendarReader: Re-occuring events not supported: " + summary);
                continue;
            } else if (dtstartdate == null || dtenddate == null) {
                M_log.warn("IcalendarReader: DTSTART/DTEND required: " + summary);
                continue;
            }

            int durationsecs = (int) ((dtenddate.getDate().getTime() - dtstartdate.getDate().getTime()) / 1000);
            int durationminutes = (durationsecs / 60) % 60;
            int durationhours = (durationsecs / (60 * 60)) % 24;

            // Put duration in proper format (hh:mm or mm) if less than 1 hour
            if (durationminutes < 10) {
                durationformat = "0" + durationminutes;
            } else {
                durationformat = "" + durationminutes;
            }

            if (durationhours != 0) {
                durationformat = durationhours + ":" + durationformat;
            }

            String description = "";
            if (component.getProperty("DESCRIPTION") != null)
                description = component.getProperty("DESCRIPTION").getValue();

            String location = "";
            if (component.getProperty("LOCATION") != null)
                location = component.getProperty("LOCATION").getValue();

            String columns[] = { component.getProperty("SUMMARY").getValue(), description,
                    DateFormat.getDateInstance(DateFormat.SHORT, rb.getLocale()).format(dtstartdate.getDate()),
                    DateFormat.getTimeInstance(DateFormat.SHORT, rb.getLocale()).format(dtstartdate.getDate()),
                    durationformat, location };

            // Remove trailing/leading quotes from all columns.
            //trimLeadingTrailingQuotes(columns);

            handler.handleRow(processLine(columnDescriptionArray, lineNumber, columns));

            lineNumber++;

        } // end for

    } catch (Exception e) {
        M_log.warn(".importSteamFromDelimitedFile(): ", e);
    }
}

From source file:org.openmrs.web.WebUtil.java

public static String formatDate(Date date, Locale locale, FORMAT_TYPE type) {
    log.debug("Formatting date: " + date + " with locale " + locale);

    DateFormat dateFormat = null;

    if (type == FORMAT_TYPE.TIMESTAMP) {
        String dateTimeFormat = Context.getAdministrationService()
                .getGlobalPropertyValue(OpenmrsConstants.GP_SEARCH_DATE_DISPLAY_FORMAT, null);
        if (StringUtils.isEmpty(dateTimeFormat)) {
            dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
        } else {/*from   w w w  .j a v a2s .  co m*/
            dateFormat = new OpenmrsDateFormat(new SimpleDateFormat(dateTimeFormat), locale);
        }
    } else if (type == FORMAT_TYPE.TIME) {
        String timeFormat = Context.getAdministrationService()
                .getGlobalPropertyValue(OpenmrsConstants.GP_SEARCH_DATE_DISPLAY_FORMAT, null);
        if (StringUtils.isEmpty(timeFormat)) {
            dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
        } else {
            dateFormat = new OpenmrsDateFormat(new SimpleDateFormat(timeFormat), locale);
        }
    } else if (type == FORMAT_TYPE.DATE) {
        String formatValue = Context.getAdministrationService()
                .getGlobalPropertyValue(OpenmrsConstants.GP_SEARCH_DATE_DISPLAY_FORMAT, "");
        if (StringUtils.isEmpty(formatValue)) {
            dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
        } else {
            dateFormat = new OpenmrsDateFormat(new SimpleDateFormat(formatValue), locale);
        }
    }
    return date == null ? "" : dateFormat.format(date);
}