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:DateFormatDemo.java

static public void showTimeStyles(Locale currentLocale) {

    Date today = new Date();
    String result;/* w  ww  .  java  2  s  . c o m*/
    DateFormat formatter;

    int[] styles = { DateFormat.DEFAULT, DateFormat.SHORT, DateFormat.MEDIUM, DateFormat.LONG,
            DateFormat.FULL };

    System.out.println();
    System.out.println("Locale: " + currentLocale.toString());
    System.out.println();

    for (int k = 0; k < styles.length; k++) {
        formatter = DateFormat.getTimeInstance(styles[k], currentLocale);
        result = formatter.format(today);
        System.out.println(result);
    }
}

From source file:com.jslsolucoes.tagria.lib.util.TagUtil.java

public static String format(String type, String value, JspContext jspContext) {

    if (StringUtils.isEmpty(value)) {
        return value;
    } else if ("date".equals(type) || "timestamp".equals(type) || "hour".equals(type)) {

        DateFormat dateFormat = DateFormat.getDateTimeInstance();
        if ("timestamp".equals(type)) {
            dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM,
                    locale(jspContext));
        } else if ("date".equals(type)) {
            dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale(jspContext));
        } else if ("hour".equals(type)) {
            dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale(jspContext));
        }/*from   ww w .  ja  v a 2 s  .c  om*/
        List<String> patterns = new ArrayList<>();
        patterns.add("yyyy-MM-dd HH:mm:ss");
        patterns.add("yyyy-MM-dd");
        patterns.add("E MMM dd HH:mm:ss zzz yyyy");
        for (String pattern : patterns) {
            try {
                return dateFormat.format(new SimpleDateFormat(pattern, Locale.ENGLISH).parse(value));
            } catch (ParseException pe) {
                //Try another format
            }
        }
        return value;
    } else if ("currency".equals(type)) {
        DecimalFormat nf = new DecimalFormat("#,##0.00", new DecimalFormatSymbols(locale(jspContext)));
        return nf.format(new Double(value));
    } else if ("cep".equals(type)) {
        return String.format("%08d", Long.valueOf(value)).replaceAll("^([0-9]{5})([0-9]{3})$", "$1-$2");
    } else if ("cpf".equals(type)) {
        return String.format("%011d", Long.valueOf(value))
                .replaceAll("^([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{2})$", "$1.$2.$3-$4");
    } else if ("cnpj".equals(type)) {
        return String.format("%014d", Long.valueOf(value))
                .replaceAll("^([0-9]{2})([0-9]{3})([0-9]{3})([0-9]{4})([0-9]{2})$", "$1.$2.$3/$4-$5");
    } else if ("tel".equals(type)) {
        return String.format("%010d", Long.valueOf(value)).replaceAll("^([0-9]{2})([0-9]{4,5})([0-9]{4})$",
                "($1) $2-$3");
    }
    return value;
}

From source file:org.olat.commons.calendar.ui.components.FullCalendarComponentRenderer.java

@Override
public void render(Renderer renderer, StringOutput sb, Component source, URLBuilder ubu, Translator translator,
        RenderResult renderResult, String[] args) {

    FullCalendarComponent fcC = (FullCalendarComponent) source;
    FullCalendarElement fcE = fcC.getCalendarElement();
    Form rootForm = fcE.getRootForm();//  w  w w . j  a v  a 2  s . c  o m
    String id = "o_c" + fcC.getDispatchID();
    String formId = fcE.getFormDispatchId();
    String printId = "fc_p" + fcC.getDispatchID();

    Calendar cal = Calendar.getInstance(fcC.getTranslator().getLocale());
    int firstDay = cal.getFirstDayOfWeek() - 1;
    cal = Calendar.getInstance();
    cal.setTime(fcC.getCurrentDate());

    Calendar calRef = Calendar.getInstance(fcC.getTranslator().getLocale());
    calRef.set(Calendar.DATE, 25);
    calRef.set(Calendar.MONTH, 11);
    calRef.set(Calendar.YEAR, 2013);

    String formatted = DateFormat.getDateInstance(DateFormat.SHORT, fcC.getTranslator().getLocale())
            .format(calRef.getTime());
    boolean firstMonth = (formatted.indexOf("12") < formatted.indexOf("25"));

    String amFormatted = DateFormat.getTimeInstance(DateFormat.SHORT, fcC.getTranslator().getLocale())
            .format(calRef.getTime());
    boolean ampm = amFormatted.contains("AM") || amFormatted.contains("PM");

    sb.append("<script type='text/javascript'>\n").append("/* <![CDATA[ */ \n").append("jQuery(function() {\n")
            .append("   jQuery('#").append(id).append("').fullCalendar( {\n").append("   header: {\n")
            .append("     left: 'prev,print,next today',\n").append("     center: 'title',\n")
            .append("     right: 'month,agendaWeek,agendaDay'\n").append("   },\n").append("   buttonText: {\n")
            .append("     today: '").append(escapeJavaScript(translator.translate("cal.thisweek")))
            .append("',\n").append("     month: '").append(escapeJavaScript(translator.translate("cal.month")))
            .append("',\n").append("     day: '").append(escapeJavaScript(translator.translate("cal.day")))
            .append("',\n").append("     week: '").append(escapeJavaScript(translator.translate("cal.week")))
            .append("',\n").append("     print: '").append(escapeJavaScript(translator.translate("print")))
            .append("'\n").append("   },\n").append("   monthNames: ").append(getMonthLong(translator))
            .append(",\n").append("   monthNamesShort: ").append(getMonthShort(translator)).append(",\n")
            .append("   dayNames: ").append(getDayLong(translator)).append(",\n").append("   dayNamesShort: ")
            .append(getDayShort(translator)).append(",\n").append("   allDayText:'")
            .append(translator.translate("cal.form.allday")).append("',\n").append("   axisFormat:'")
            .append(ampm ? "h(:mm)tt" : "H.mm").append("',\n").append("   timeFormat:'")
            .append(ampm ? "h(:mm)tt" : "H.mm").append("',\n").append("   titleFormat: {\n")
            .append("     month: 'MMMM yyyy',\n").append("     week: ")
            .append(firstMonth ? "\"MMM d[ yyyy]{ '&#8212;'[ MMM] d yyyy}\""
                    : "\"d. [ MMM] [ yyyy]{ '&#8212;' d. MMM yyyy}\"")
            .append(",\n").append("     day: ")
            .append(firstMonth ? "'dddd, MMM d, yyyy'" : "'dddd, d. MMM yyyy'").append("\n").append("   },\n")
            .append("   columnFormat: {\n").append("     month: 'ddd',\n").append("     week: ")
            .append(firstMonth ? "'ddd M/d'" : "'ddd d.M.'").append(",\n").append("     day: ")
            .append(firstMonth ? "'dddd M/d'" : "'dddd d.M.'").append("\n").append("   },\n").append("   year:")
            .append(cal.get(Calendar.YEAR)).append(",\n").append("   month:").append(cal.get(Calendar.MONTH))
            .append(",\n").append("   date:").append(cal.get(Calendar.DAY_OF_MONTH)).append(",\n")
            .append("   firstDay:").append(firstDay).append(",\n").append("   defaultView:'")
            .append(fcC.getViewName()).append("',\n").append("   weekNumbers: true,\n")
            .append("   editable: true,\n").append("   selectable: true,\n").append("   selectHelper: true,\n")
            .append("     eventSources:[");
    int count = 0;
    for (KalendarRenderWrapper calWrapper : fcC.getKalendarRenderWrappers()) {
        if (calWrapper.getKalendarConfig().isVis()) {
            String calId = calWrapper.getKalendar().getCalendarID();
            String color = calWrapper.getKalendarConfig().getCss();
            if (StringHelper.containsNonWhitespace(color) && color.startsWith("o_cal_")) {
                color = color.substring(6, color.length());
            }
            if (count++ != 0)
                sb.append(",");
            sb.append("{\n").append("   url:'").append(fcC.getMapperUrl()).append("/").append(calId)
                    .append(".json',\n").append("   color:'").append(color).append("'\n").append("}");
        }
    }
    sb.append("   ],\n").append("   eventAfterRender: function(event, element, view) {\n")
            .append("     element.each(function(index, el) {\n")
            .append("       jQuery(el).attr('id', 'o_cev_' + view.name + '_' + event.id);\n")
            .append("     });\n").append("   },\n").append("   viewDisplay: function(view) {\n")
            .append(FormJSHelper.generateXHRFnCallVariables(rootForm, formId, 1))
            .append("     o_ffXHREvent(formNam, dispIdField, dispId, eventIdField, eventInt,'evChangeView',view.name,'start',view.start.getTime());\n")
            .append("   },\n")
            .append("     eventDrop: function(calEvent, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {\n")
            .append(FormJSHelper.generateXHRFnCallVariables(rootForm, formId, 1))
            .append("     o_ffXHREvent(formNam, dispIdField, dispId, eventIdField, eventInt,'evMove',calEvent.id,'dayDelta',dayDelta,'minuteDelta',minuteDelta,'allDay',allDay);\n")
            .append("     },\n").append("   select: function(startDate, endDate, allDay, jsEvent, view) {\n")
            .append(FormJSHelper.generateXHRFnCallVariables(rootForm, formId, 1))
            .append("     o_ffXHREvent(formNam, dispIdField, dispId, eventIdField, eventInt,'evAdd','new','start',startDate.getTime(),'end',endDate.getTime(),'allDay',allDay);\n")
            .append("   },\n").append("   eventClick: function(calEvent, jsEvent, view) {\n")
            .append(FormJSHelper.generateXHRFnCallVariables(rootForm, formId, 1))
            .append("     o_ffXHREvent(formNam, dispIdField, dispId, eventIdField, eventInt,'evSelect',calEvent.id,'evDomId','o_cev_' + view.name + '_' + calEvent.id);\n")
            .append("   }\n").append(" });\n")
            .append(" jQuery('.fc-header-left').append('<span class=\"fc-header-space\"></span><span id=\"")
            .append(printId)
            .append("\" class=\"fc-button fc-button-print fc-state-default fc-corner-left fc-corner-right\"><span>")
            .append(translator.translate("print")).append("</span></span>');\n")
            .append(" jQuery('.fc-button-print').click(function () {\n")
            .append(FormJSHelper.generateXHRFnCallVariables(rootForm, formId, 1))
            .append("   o_ffXHREvent(formNam, dispIdField, dispId, eventIdField, eventInt,'print','print');\n")
            .append(" });\n").append("});\n").append("/* ]]> */\n").append("</script>");
}

From source file:DateUtil.java

/**
 * Formats given time according to specified locale and time style
 *
 * @param time      Time to convert/*from  w  w w  . j a v a 2 s  .  co  m*/
 * @param locale    Locale to use for formatting time
 * @param timeStyle Time style
 * @return String representation of time according to given locale and time style
 * @see java.text.DateFormat
 */
public static String formatTime(Date time, Locale locale, int timeStyle) {
    DateFormat formatter = DateFormat.getTimeInstance(timeStyle, locale);
    return formatter.format(time);
}

From source file:de.perdian.commons.lang.conversion.impl.converters.StringToDateConverter.java

@Override
protected DateFormat resolveDefaultFormat(Locale locale) {
    String pattern = this.getPattern();
    if (pattern != null) {
        return new SimpleDateFormat(pattern, locale);
    } else {//from  w  w  w .  jav a 2  s  .  c  o m
        Class<? extends Date> targetDateClass = this.getTargetDateClass();
        if (targetDateClass == null || targetDateClass.equals(java.util.Date.class)
                || targetDateClass.equals(java.sql.Date.class)) {
            return DateFormat.getDateInstance(DateFormat.DEFAULT, locale);
        } else if (targetDateClass.equals(java.sql.Timestamp.class)) {
            return DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, locale);
        } else if (targetDateClass.equals(java.sql.Time.class)) {
            return DateFormat.getTimeInstance(DateFormat.DEFAULT, locale);
        } else {
            return DateFormat.getInstance();
        }
    }
}

From source file:dev.memento.MementoClient.java

/**
 * //from ww  w  . ja  va  2 s .  c o  m
 */
public MementoClient() {
    // Set the date and time format
    SimpleDateTime.mDateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US);
    SimpleDateTime.mTimeFormat = DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.US);

    // Holds all the timemaps for the web page being viewed
    mTimeMaps = new HashSet<TimeMap>();
    mMementos = new MementoList();

}

From source file:com.sonicle.webtop.core.util.AppLocale.java

private SimpleDateFormat getTimeFormatter(int style, Locale locale) {
    return (SimpleDateFormat) DateFormat.getTimeInstance(style, locale);
}

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

License:asdf

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

From source file:com.stefanbrenner.droplet.model.internal.DropletContext.java

@Override
public void addLoggingMessage(final String message) {
    String oldValue = getLoggingMessages();
    loggingMessages = new ArrayList<String>(loggingMessages);

    // add timestamp to message
    DateFormat format = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.getDefault());
    String timestamp = format.format(new Date(System.currentTimeMillis()));
    String logEntry = timestamp + ": " + message; //$NON-NLS-1$

    loggingMessages.add(logEntry);//  ww w  .j a va2 s.  c o m

    firePropertyChange(IDropletContext.PROPERTY_LOGGING, oldValue, getLoggingMessages());
}

From source file:lucee.commons.i18n.FormatUtil.java

public static DateFormat[] getTimeFormats(Locale locale, TimeZone tz, boolean lenient) {
    String id = "t-" + locale.hashCode() + "-" + tz.getID() + "-" + lenient;
    DateFormat[] df = formats.get(id);
    if (df == null) {
        List<DateFormat> list = new ArrayList<DateFormat>();
        list.add(DateFormat.getTimeInstance(DateFormat.FULL, locale));
        list.add(DateFormat.getTimeInstance(DateFormat.LONG, locale));
        list.add(DateFormat.getTimeInstance(DateFormat.MEDIUM, locale));
        list.add(DateFormat.getTimeInstance(DateFormat.SHORT, locale));
        add24(list, locale);/*from  w  w  w.  j a  v a  2  s.com*/
        addCustom(list, locale, FORMAT_TYPE_TIME);
        df = list.toArray(new DateFormat[list.size()]);

        for (int i = 0; i < df.length; i++) {
            df[i].setLenient(lenient);
            df[i].setTimeZone(tz);
        }
        formats.put(id, df);
    }
    return df;
}