Example usage for java.text DateFormat MEDIUM

List of usage examples for java.text DateFormat MEDIUM

Introduction

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

Prototype

int MEDIUM

To view the source code for java.text DateFormat MEDIUM.

Click Source Link

Document

Constant for medium style pattern.

Usage

From source file:org.whisperim.android.ui.ChatWindow.java

private void appendMessage(Message m) {
    DateFormat d = DateFormat.getTimeInstance(DateFormat.MEDIUM);
    messageHistory_.setText(messageHistory_.getText() + m.getFromBuddy().getAlias() + " ("
            + d.format(m.getTimeSent()) + "): " + m.getMessage() + "\n");
}

From source file:io.wcm.devops.conga.generator.FileGenerator.java

/**
 * Generate comment lines for file header added to all files for which a {@link FileHeaderPlugin} is registered.
 * @param dependencyVersions List of artifact versions to include
 * @return Formatted comment lines/*from ww w.j  a v  a2  s  .  c  o m*/
 */
private List<String> buildFileHeaderCommentLines(String version, List<String> dependencyVersions) {
    List<String> lines = new ArrayList<>();

    lines.add("This file is AUTO-GENERATED by CONGA. Please do no change it manually.");
    lines.add("");
    lines.add((version != null ? "Version " + version + ", generated " : "Generated ") + "at: "
            + DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(new Date()));

    // add information how this file was generated
    lines.add("Environment: " + environmentName);
    lines.add("Role: " + roleName);
    if (StringUtils.isNotBlank(roleVariantName)) {
        lines.add("Variant: " + roleVariantName);
    }
    lines.add("Template: " + templateName);

    if (dependencyVersions != null && !dependencyVersions.isEmpty()) {
        lines.add("");
        lines.add("Dependencies:");
        lines.addAll(dependencyVersions);
    }

    return formatFileHeaderCommentLines(lines);
}

From source file:org.openmrs.web.taglib.FormatDateTag.java

public int doStartTag() {
    RequestContext requestContext = (RequestContext) this.pageContext
            .getAttribute(RequestContextAwareTag.REQUEST_CONTEXT_PAGE_ATTRIBUTE);

    if (date == null && getPath() != null) {
        try {// w  w w . java2 s  . c o m
            // get the "path" object from the pageContext
            String resolvedPath = getPath();
            String nestedPath = (String) pageContext.getAttribute(NestedPathTag.NESTED_PATH_VARIABLE_NAME,
                    PageContext.REQUEST_SCOPE);
            if (nestedPath != null) {
                resolvedPath = nestedPath + resolvedPath;
            }

            BindStatus status = new BindStatus(requestContext, resolvedPath, false);
            log.debug("status: " + status);

            if (status.getValue() != null) {
                log.debug("status.value: " + status.getValue());
                if (status.getValue().getClass() == Date.class) {
                    // if no editor was registered all will go well here
                    date = (Date) status.getValue();
                } else {
                    // if a "Date" property editor was registerd for the form, the status.getValue()
                    // object will be a java.lang.String.  This is useless.  Try getting the original
                    // value from the troublesome editor
                    log.debug("status.valueType: " + status.getValueType());
                    Timestamp timestamp = (Timestamp) status.getEditor().getValue();
                    date = new Date(timestamp.getTime());
                }
            }
        } catch (Exception e) {
            log.warn("Unable to get a date object from path: " + getPath(), e);
            return SKIP_BODY;
        }
    }

    if (!dateWasSet && date == null) {
        log.warn("Both 'date' and 'path' cannot be null.  Page: " + pageContext.getPage() + " localname:"
                + pageContext.getRequest().getLocalName() + " rd:"
                + pageContext.getRequest().getRequestDispatcher(""));
        return SKIP_BODY;
    }

    if (type == null) {
        type = "";
    }

    DateFormat dateFormat = null;

    if (format != null && format.length() > 0) {
        dateFormat = new SimpleDateFormat(format, Context.getLocale());
    } else if (type.equals("xml")) {
        dateFormat = new SimpleDateFormat("dd-MMM-yyyy", Context.getLocale());
    } else {
        log.debug("context locale: " + Context.getLocale());

        if (type.equals("long")) {
            dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Context.getLocale());
        } else if (type.equals("medium")) {
            dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Context.getLocale());
        } else {
            dateFormat = Context.getDateFormat();
        }
    }

    if (dateFormat == null) {
        dateFormat = new SimpleDateFormat("MM-dd-yyyy");
    }

    String datestr = "";

    try {
        if (date != null) {
            if (type.equals("milliseconds")) {
                datestr = "" + date.getTime();
            } else {
                if (showTodayOrYesterday && (DateUtils.isSameDay(Calendar.getInstance().getTime(), date)
                        || OpenmrsUtil.isYesterday(date))) {
                    //print only time of day but maintaining the format(24 Vs 12) if any was specified
                    String timeFormatString = (format != null && !format.contains("a")) ? "HH:mm" : "h:mm a";
                    dateFormat = new SimpleDateFormat(timeFormatString);
                    if (DateUtils.isSameDay(Calendar.getInstance().getTime(), date)) {
                        datestr = Context.getMessageSourceService().getMessage("general.today") + " "
                                + dateFormat.format(date);
                    } else {
                        datestr = Context.getMessageSourceService().getMessage("general.yesterday") + " "
                                + dateFormat.format(date);
                    }
                } else {
                    datestr = dateFormat.format(date);
                }
            }
        }
    } catch (IllegalArgumentException e) {
        //format or date is invalid
        log.error("date: " + date);
        log.error("format: " + format);
        log.error(e);
        datestr = date.toString();
    }

    try {
        pageContext.getOut().write(datestr);
    } catch (IOException e) {
        log.error(e);
    }

    // reset the objects to null because taglibs are reused
    release();

    return SKIP_BODY;
}

From source file:org.apache.fop.tools.anttasks.FileCompare.java

private void writeHeader(PrintWriter results) {
    String dateTime = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM).format(new Date());
    results.println("<html><head><title>Test Results</title></head><body>\n");
    results.println("<h2>Compare Results<br>");
    results.println("<font size='1'>created " + dateTime + "</font></h2>");
    results.println("<table cellpadding='10' border='2'><thead>" + "<th align='center'>reference file</th>"
            + "<th align='center'>test file</th>" + "<th align='center'>identical?</th></thead>");
}

From source file:com.bdb.weather.display.stripchart.StripChart.java

private void createRenderer(int dataset, TimeSeriesCollection collection, NumberFormat format) {
    DefaultXYItemRenderer renderer = new DefaultXYItemRenderer();
    renderer.setBaseShapesVisible(false);

    renderer.setBaseToolTipGenerator(//from   w w w  . j a  v a 2s . co m
            new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                    DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG), format));

    renderer.setDefaultEntityRadius(1);
    plot.setRenderer(dataset, renderer);
    plot.setDataset(dataset, collection);
}

From source file:org.openvpms.report.AbstractExpressionEvaluator.java

/**
 * Returns the formatted value of an expression.
 *
 * @param expression the expression//from  w ww .  j  av  a2  s  . co  m
 * @return the result of the expression
 */
@Override
public String getFormattedValue(String expression) {
    Object value = getValue(expression);
    if (value instanceof Date) {
        Date date = (Date) value;
        return DateFormat.getDateInstance(DateFormat.MEDIUM).format(date);
    } else if (value instanceof Money) {
        return NumberFormat.getCurrencyInstance().format(value);
    } else if (value instanceof BigDecimal) {
        DecimalFormat format = new DecimalFormat("#,##0.00;-#,##0.00");
        return format.format(value);
    } else if (value instanceof IMObject) {
        return getValue((IMObject) value);
    } else if (value instanceof IMObjectReference) {
        return getValue((IMObjectReference) value);
    } else if (value != null) {
        return value.toString();
    }
    return null;
}

From source file:com.trenako.entities.CollectionItem.java

public String getAddedDay() {
    if (addedAt == null) {
        return "";
    }// ww  w . java2s .c o m

    DateFormat df = SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
    return df.format(addedAt);
}

From source file:at.alladin.rmbt.controlServer.TestResultResource.java

@Post("json")
public String request(final String entity) {
    long startTime = System.currentTimeMillis();
    addAllowOrigin();// w w w.  jav  a  2  s . c  o  m

    JSONObject request = null;

    final ErrorList errorList = new ErrorList();
    final JSONObject answer = new JSONObject();
    String answerString;

    final String clientIpRaw = getIP();
    System.out.println(MessageFormat.format(labels.getString("NEW_TESTRESULT"), clientIpRaw));

    if (entity != null && !entity.isEmpty())
        // try parse the string to a JSON object
        try {
            request = new JSONObject(entity);

            String lang = request.optString("language");

            // Load Language Files for Client

            final List<String> langs = Arrays
                    .asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*"));

            if (langs.contains(lang)) {
                errorList.setLanguage(lang);
                labels = ResourceManager.getSysMsgBundle(new Locale(lang));
            } else
                lang = settings.getString("RMBT_DEFAULT_LANGUAGE");

            //                System.out.println(request.toString(4));

            if (conn != null) {
                final Client client = new Client(conn);
                final Test test = new Test(conn);

                final String testUuid = request.optString("test_uuid");
                if (testUuid != null && test.getTestByUuid(UUID.fromString(testUuid)) > 0
                        && client.getClientByUid(test.getField("client_id").intValue())
                        && "FINISHED".equals(test.getField("status").toString())) {

                    final Locale locale = new Locale(lang);
                    final Format format = new SignificantFormat(2, locale);

                    final JSONArray resultList = new JSONArray();

                    final JSONObject jsonItem = new JSONObject();

                    JSONArray jsonItemList = new JSONArray();

                    // RMBTClient Info
                    //also send open-uuid (starts with 'P')
                    final String openUUID = "P" + ((UUIDField) test.getField("open_uuid")).toString();
                    jsonItem.put("open_uuid", openUUID);

                    //and open test-uuid (starts with 'O')
                    final String openTestUUID = "O" + ((UUIDField) test.getField("open_test_uuid")).toString();
                    jsonItem.put("open_test_uuid", openTestUUID);

                    final Date date = ((TimestampField) test.getField("time")).getDate();
                    final long time = date.getTime();
                    final String tzString = test.getField("timezone").toString();
                    final TimeZone tz = TimeZone.getTimeZone(tzString);
                    jsonItem.put("time", time);
                    jsonItem.put("timezone", tzString);
                    final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
                            DateFormat.MEDIUM, locale);
                    dateFormat.setTimeZone(tz);
                    final String timeString = dateFormat.format(date);
                    jsonItem.put("time_string", timeString);

                    final Field fieldDown = test.getField("speed_download");
                    JSONObject singleItem = new JSONObject();
                    singleItem.put("title", labels.getString("RESULT_DOWNLOAD"));
                    final String downloadString = String.format("%s %s",
                            format.format(fieldDown.doubleValue() / 1000d),
                            labels.getString("RESULT_DOWNLOAD_UNIT"));
                    singleItem.put("value", downloadString);
                    singleItem.put("classification",
                            Classification.classify(classification.THRESHOLD_DOWNLOAD, fieldDown.intValue()));

                    jsonItemList.put(singleItem);

                    final Field fieldUp = test.getField("speed_upload");
                    singleItem = new JSONObject();
                    singleItem.put("title", labels.getString("RESULT_UPLOAD"));
                    final String uploadString = String.format("%s %s",
                            format.format(fieldUp.doubleValue() / 1000d),
                            labels.getString("RESULT_UPLOAD_UNIT"));
                    singleItem.put("value", uploadString);
                    singleItem.put("classification",
                            Classification.classify(classification.THRESHOLD_UPLOAD, fieldUp.intValue()));

                    jsonItemList.put(singleItem);

                    final Field fieldPing = test.getField("ping_median");
                    String pingString = "";
                    if (!fieldPing.isNull()) {
                        final double pingValue = fieldPing.doubleValue() / 1000000d;
                        singleItem = new JSONObject();
                        singleItem.put("title", labels.getString("RESULT_PING"));
                        pingString = String.format("%s %s", format.format(pingValue),
                                labels.getString("RESULT_PING_UNIT"));
                        singleItem.put("value", pingString);
                        singleItem.put("classification",
                                Classification.classify(classification.THRESHOLD_PING, fieldPing.longValue()));

                        jsonItemList.put(singleItem);
                    }

                    final int networkType = test.getField("network_type").intValue();

                    final Field signalField = test.getField("signal_strength"); // signal strength as RSSI (GSM, UMTS, Wifi, sometimes LTE)
                    final Field lteRsrpField = test.getField("lte_rsrp"); // signal strength as RSRP, used in LTE
                    String signalString = null;
                    if (!signalField.isNull() || !lteRsrpField.isNull()) {
                        if (lteRsrpField.isNull()) { // only RSSI value, output RSSI to JSON  
                            final int signalValue = signalField.intValue();
                            final int[] threshold = networkType == 99 || networkType == 0
                                    ? classification.THRESHOLD_SIGNAL_WIFI
                                    : classification.THRESHOLD_SIGNAL_MOBILE;
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_SIGNAL"));
                            signalString = signalValue + " " + labels.getString("RESULT_SIGNAL_UNIT");
                            singleItem.put("value", signalString);
                            singleItem.put("classification", Classification.classify(threshold, signalValue));
                        } else { // use RSRP value else (RSRP value has priority if both are available (e.g. 3G/4G-test))
                            final int signalValue = lteRsrpField.intValue();
                            final int[] threshold = classification.THRESHOLD_SIGNAL_RSRP;
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_SIGNAL_RSRP"));
                            signalString = signalValue + " " + labels.getString("RESULT_SIGNAL_UNIT");
                            singleItem.put("value", signalString);
                            singleItem.put("classification", Classification.classify(threshold, signalValue));

                        }
                        jsonItemList.put(singleItem);
                    }

                    jsonItem.put("measurement", jsonItemList);

                    jsonItemList = new JSONArray();

                    singleItem = new JSONObject();
                    singleItem.put("title", labels.getString("RESULT_NETWORK_TYPE"));
                    final String networkTypeString = Helperfunctions.getNetworkTypeName(networkType);
                    singleItem.put("value", networkTypeString);

                    jsonItemList.put(singleItem);

                    if (networkType == 98 || networkType == 99) // mobile wifi or browser
                    {
                        final Field providerNameField = test.getField("provider_id_name");
                        if (!providerNameField.isNull()) {
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_OPERATOR_NAME"));
                            singleItem.put("value", providerNameField.toString());
                            jsonItemList.put(singleItem);
                        }
                        if (networkType == 99) // mobile wifi
                        {
                            final Field ssid = test.getField("wifi_ssid");
                            if (!ssid.isNull()) {
                                singleItem = new JSONObject();
                                singleItem.put("title", labels.getString("RESULT_WIFI_SSID"));
                                singleItem.put("value", ssid.toString());
                                jsonItemList.put(singleItem);
                            }

                        }
                    } else // mobile
                    {
                        final Field operatorNameField = test.getField("network_operator_name");
                        if (!operatorNameField.isNull()) {
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_OPERATOR_NAME"));
                            singleItem.put("value", operatorNameField.toString());
                            jsonItemList.put(singleItem);
                        }

                        final Field roamingTypeField = test.getField("roaming_type");
                        if (!roamingTypeField.isNull() && roamingTypeField.intValue() > 0) {
                            singleItem = new JSONObject();
                            singleItem.put("title", labels.getString("RESULT_ROAMING"));
                            singleItem.put("value",
                                    Helperfunctions.getRoamingType(labels, roamingTypeField.intValue()));
                            jsonItemList.put(singleItem);
                        }
                    }

                    jsonItem.put("net", jsonItemList);

                    final Field latField = test.getField("geo_lat");
                    final Field longField = test.getField("geo_long");
                    boolean includeLocation = false;
                    final Field accuracyField = test.getField("geo_accuracy");
                    if (!(latField.isNull() || longField.isNull() || accuracyField.isNull())) {
                        final double accuracy = accuracyField.doubleValue();
                        if (accuracy < Double.parseDouble(getSetting("rmbt_geo_accuracy_button_limit", lang))) {
                            includeLocation = true;
                            jsonItem.put("geo_lat", latField.doubleValue());
                            jsonItem.put("geo_long", longField.doubleValue());
                        }
                    }

                    //geo location
                    JSONObject locationJson = TestResultDetailResource.getGeoLocation(this, test, settings,
                            conn, labels);
                    if (locationJson != null) {
                        if (locationJson.has("location")) {
                            jsonItem.put("location", locationJson.getString("location"));
                        }
                        if (locationJson.has("motion")) {
                            jsonItem.put("motion", locationJson.getString("motion"));
                        }
                    }

                    resultList.put(jsonItem);

                    final Field zip_code = test.getField("zip_code");
                    if (!zip_code.isNull())
                        jsonItem.put("zip_code", zip_code.intValue());

                    final Field zip_code_geo = test.getField("zip_code_geo");
                    if (!zip_code_geo.isNull())
                        jsonItem.put("zip_code_geo", zip_code_geo.intValue());

                    String providerString = test.getField("provider_id_name").toString();
                    if (providerString == null)
                        providerString = "";
                    String platformString = test.getField("plattform").toString();
                    if (platformString == null)
                        platformString = "";
                    String modelString = test.getField("model_fullname").toString();
                    if (modelString == null)
                        modelString = "";

                    String mobileNetworkString = null;
                    final Field networkOperatorField = test.getField("network_operator");
                    final Field mobileProviderNameField = test.getField("mobile_provider_name");
                    if (!networkOperatorField.isNull()) {
                        if (mobileProviderNameField.isNull())
                            mobileNetworkString = networkOperatorField.toString();
                        else
                            mobileNetworkString = String.format("%s (%s)", mobileProviderNameField,
                                    networkOperatorField);
                    }

                    /*
                    RESULT_SHARE_TEXT = My Result:\nDate/time: {0}\nDownload: {1}\nUpload: {2}\nPing: {3}\n{4}Network type: {5}\n{6}{7}Platform: {8}\nModel: {9}\n{10}\n\n
                    RESULT_SHARE_TEXT_SIGNAL_ADD = Signal strength: {0}\n
                    RESULT_SHARE_TEXT_RSRP_ADD = Signal strength (RSRP): {0}\n
                    RESULT_SHARE_TEXT_MOBILE_ADD = Mobile network: {0}\n
                    RESULT_SHARE_TEXT_PROVIDER_ADD = Operator: {0}\n
                            
                    */
                    String shareTextField4 = "";
                    if (signalString != null) //info on signal strength, field 4
                        if (lteRsrpField.isNull()) { //add RSSI if RSRP is not available
                            shareTextField4 = MessageFormat
                                    .format(labels.getString("RESULT_SHARE_TEXT_SIGNAL_ADD"), signalString);
                        } else { //add RSRP
                            shareTextField4 = MessageFormat
                                    .format(labels.getString("RESULT_SHARE_TEXT_RSRP_ADD"), signalString);
                        }
                    String shareLocation = "";
                    if (includeLocation && locationJson != null) {

                        shareLocation = MessageFormat.format(labels.getString("RESULT_SHARE_TEXT_LOCATION_ADD"),
                                locationJson.getString("location"));
                    }

                    final String shareText = MessageFormat.format(labels.getString("RESULT_SHARE_TEXT"),
                            timeString, //field 0
                            downloadString, //field 1
                            uploadString, //field 2
                            pingString, //field 3
                            shareTextField4, //contains field 4
                            networkTypeString, //field 5
                            providerString.isEmpty() ? ""
                                    : MessageFormat.format(labels.getString("RESULT_SHARE_TEXT_PROVIDER_ADD"),
                                            providerString), //field 6
                            mobileNetworkString == null ? ""
                                    : MessageFormat.format(labels.getString("RESULT_SHARE_TEXT_MOBILE_ADD"),
                                            mobileNetworkString), //field 7
                            platformString, //field 8
                            modelString, //field 9
                            //dz add location
                            shareLocation, //field 10
                            getSetting("url_open_data_prefix", lang) + openTestUUID); //field 11
                    jsonItem.put("share_text", shareText);

                    final String shareSubject = MessageFormat.format(labels.getString("RESULT_SHARE_SUBJECT"),
                            timeString //field 0
                    );
                    jsonItem.put("share_subject", shareSubject);

                    jsonItem.put("network_type", networkType);

                    if (resultList.length() == 0)
                        errorList.addError("ERROR_DB_GET_TESTRESULT");
                    // errorList.addError(MessageFormat.format(labels.getString("ERROR_DB_GET_CLIENT"),
                    // new Object[] {uuid}));

                    answer.put("testresult", resultList);
                } else
                    errorList.addError("ERROR_REQUEST_NO_UUID");

            } else
                errorList.addError("ERROR_DB_CONNECTION");

        } catch (final JSONException e) {
            errorList.addError("ERROR_REQUEST_JSON");
            System.out.println("Error parsing JSDON Data " + e.toString());
        }
    else
        errorList.addErrorString("Expected request is missing.");

    try {
        answer.putOpt("error", errorList.getList());
    } catch (final JSONException e) {
        System.out.println("Error saving ErrorList: " + e.toString());
    }

    answerString = answer.toString();

    long elapsedTime = System.currentTimeMillis() - startTime;
    System.out.println(MessageFormat.format(labels.getString("NEW_TESTRESULT_SUCCESS"), clientIpRaw,
            Long.toString(elapsedTime)));

    return answerString;
}

From source file:DateUtil.java

/**
 * Parses given string according to specified locale and <code>DateFormat.MEDIUM</code> style
 *
 * @param source Source string to parse time from
 * @param locale Locale to use for parsing time
 * @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 <code>DateFormat.MEDIUM</code> style
 * @see java.text.DateFormat//from w  w  w. j a  v a 2 s  .c  o m
 * @see java.text.DateFormat#MEDIUM
 */
public static Date parseTime(String source, Locale locale) throws ParseException {
    return parseTime(source, locale, DateFormat.MEDIUM);
}

From source file:org.sakaiproject.profile2.util.ProfileUtils.java

/**
 * Convert a Date into a String according to format, or, if format
 * is set to null, do a current locale based conversion.
 *
 * @param date         date to convert//from w  w  w.java  2  s . c om
 * @param format      format in SimpleDateFormat syntax. Set to null to force as locale based conversion.
 */
public static String convertDateToString(Date date, String format) {

    if (date == null || "".equals(format)) {
        throw new IllegalArgumentException("Null Argument in Profile.convertDateToString()");
    }

    String dateStr = null;

    if (format != null) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        dateStr = dateFormat.format(date);
    } else {
        // Since no specific format has been specced, we use the user's locale.
        Locale userLocale = (new ResourceLoader()).getLocale();
        DateFormat formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, userLocale);
        dateStr = formatter.format(date);
    }

    if (log.isDebugEnabled()) {
        log.debug("Profile.convertDateToString(): Input date: " + date.toString());
        log.debug("Profile.convertDateToString(): Converted date string: " + dateStr);
    }

    return dateStr;
}