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) 

Source Link

Document

Gets the time formatter with the given formatting style for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:org.methodize.nntprss.admin.AdminServlet.java

private void writeFooter(Writer writer) throws IOException {
    DateFormat df = DateFormat.getTimeInstance(DateFormat.MEDIUM);

    writer.write("<p>");
    writer.write("</td></tr></table>");

    writer.write("<table cellspacing='0' cellpadding='2' width='100%'><tr><td class='row2'>nntp//rss v"
            + AppConstants.VERSION + "</td><td class='row2' align='center'>nntp//rss Time: "
            + df.format(new Date())
            + "</td><td class='row2' align='right'><a href='http://www.methodize.org/nntprss'>nntp//rss home page</a>&nbsp;&nbsp;</td></tr></table>");

    writer.write("</td></tr></table>");

    writer.write("</body></html>");
}

From source file:no.firestorm.weathernotificatonservice.WeatherNotificationService.java

/**
 * Display a notification with temperature
 * //  w  ww .ja  v a  2  s.  co  m
 * @param weather
 *            Weather element to with data to be shown in notification, if
 *            null a message for that say that this station does not provide
 *            data will be shown
 */
private void makeNotification(WeatherElement weather) {
    int tickerIcon, contentIcon;
    CharSequence tickerText, contentTitle, contentText, contentTime;
    final DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
    long when;
    Float temperatureF = null;
    if (weather != null) {
        // Has data
        final WeatherElement temperature = weather;
        // Find name
        final String stationName = WeatherNotificationSettings.getStationName(WeatherNotificationService.this);

        // Find icon
        tickerIcon = TempToDrawable.getDrawableFromTemp(Float.valueOf(temperature.getValue()));
        contentIcon = tickerIcon;
        // Set title
        tickerText = stationName;
        contentTitle = stationName;
        contentTime = df.format(temperature.getDate());
        when = temperature.getDate().getTime();

        final Context context = WeatherNotificationService.this;
        temperatureF = new Float(temperature.getValue());
        contentText = String.format("%s %.1f C", context.getString(R.string.temperatur_),
                new Float(temperature.getValue()));

        updateAlarm(weather);

    } else {
        // No data
        contentIcon = android.R.drawable.stat_notify_error;
        final Context context = WeatherNotificationService.this;
        contentTime = df.format(new Date());
        when = (new Date()).getTime();
        tickerText = context.getText(R.string.no_available_data);
        contentTitle = context.getText(R.string.no_available_data);
        contentText = context.getString(R.string.try_another_station);
        tickerIcon = android.R.drawable.stat_notify_error;

    }

    makeNotification(tickerIcon, contentIcon, tickerText, contentTitle, contentText, contentTime, when,
            temperatureF);

}

From source file:org.lunarray.model.descriptor.util.DateFormatUtil.java

/**
 * Resolves the time format./*from ww w.  j  av  a  2s.  com*/
 * 
 * @param locale
 *            The (optional) locale.
 * @return The format.
 */
private DateFormat resolveTimeFormat(final Locale locale) {
    DateFormat defaultValue;
    if (CheckUtil.isNull(locale)) {
        defaultValue = DateFormat.getTimeInstance(DateFormat.FULL);
    } else {
        defaultValue = DateFormat.getTimeInstance(DateFormat.FULL, locale);
    }
    return this.resolve(DateFormatUtil.DEFAULT_TIME_KEY, defaultValue, locale);
}

From source file:org.totschnig.myexpenses.dialog.TransactionDetailFragment.java

public void fillData(Transaction o) {
    final FragmentActivity ctx = getActivity();
    mLayout.findViewById(R.id.progress).setVisibility(View.GONE);
    mTransaction = o;//from   w w  w .  ja  v a 2  s  .  com
    if (mTransaction == null) {
        TextView error = (TextView) mLayout.findViewById(R.id.error);
        error.setVisibility(View.VISIBLE);
        error.setText(R.string.transaction_deleted);
        return;
    }
    boolean doShowPicture = false;
    if (mTransaction.getPictureUri() != null) {
        doShowPicture = true;
        if (mTransaction.getPictureUri().getScheme().equals("file")) {
            if (!new File(mTransaction.getPictureUri().getPath()).exists()) {
                Toast.makeText(getActivity(), R.string.image_deleted, Toast.LENGTH_SHORT).show();
                doShowPicture = false;
            }
        }
    }
    AlertDialog dlg = (AlertDialog) getDialog();
    if (dlg != null) {
        Button btn = dlg.getButton(AlertDialog.BUTTON_POSITIVE);
        if (btn != null) {
            if (mTransaction.crStatus != Transaction.CrStatus.VOID) {
                btn.setEnabled(true);
            } else {
                btn.setVisibility(View.GONE);
            }
        }
        btn = dlg.getButton(AlertDialog.BUTTON_NEUTRAL);
        if (btn != null) {
            btn.setVisibility(doShowPicture ? View.VISIBLE : View.GONE);
        }
    }
    mLayout.findViewById(R.id.Table).setVisibility(View.VISIBLE);
    int title;
    boolean type = mTransaction.getAmount().getAmountMinor() > 0 ? ExpenseEdit.INCOME : ExpenseEdit.EXPENSE;

    if (mTransaction instanceof SplitTransaction) {
        mLayout.findViewById(R.id.SplitContainer).setVisibility(View.VISIBLE);
        //TODO: refactor duplicated code with SplitPartList
        title = R.string.split_transaction;
        View emptyView = mLayout.findViewById(R.id.empty);

        ListView lv = (ListView) mLayout.findViewById(R.id.list);
        // Create an array to specify the fields we want to display in the list
        String[] from = new String[] { KEY_LABEL_MAIN, KEY_AMOUNT };

        // and an array of the fields we want to bind those fields to 
        int[] to = new int[] { R.id.category, R.id.amount };

        // Now create a simple cursor adapter and set it to display
        mAdapter = new SplitPartAdapter(ctx, R.layout.split_part_row, null, from, to, 0,
                mTransaction.getAmount().getCurrency());
        lv.setAdapter(mAdapter);
        lv.setEmptyView(emptyView);

        LoaderManager manager = getLoaderManager();
        if (manager.getLoader(SPLIT_PART_CURSOR) != null && !manager.getLoader(SPLIT_PART_CURSOR).isReset()) {
            manager.restartLoader(SPLIT_PART_CURSOR, null, this);
        } else {
            manager.initLoader(SPLIT_PART_CURSOR, null, this);
        }

    } else {
        if (mTransaction instanceof Transfer) {
            title = R.string.transfer;
            ((TextView) mLayout.findViewById(R.id.AccountLabel)).setText(R.string.transfer_from_account);
            ((TextView) mLayout.findViewById(R.id.CategoryLabel)).setText(R.string.transfer_to_account);
        } else {
            title = type ? R.string.income : R.string.expense;
        }
    }

    String amountText;
    String accountLabel = Account.getInstanceFromDb(mTransaction.accountId).label;
    if (mTransaction instanceof Transfer) {
        ((TextView) mLayout.findViewById(R.id.Account)).setText(type ? mTransaction.label : accountLabel);
        ((TextView) mLayout.findViewById(R.id.Category)).setText(type ? accountLabel : mTransaction.label);
        if (((Transfer) mTransaction).isSameCurrency()) {
            amountText = formatCurrencyAbs(mTransaction.getAmount());
        } else {
            String self = formatCurrencyAbs(mTransaction.getAmount());
            String other = formatCurrencyAbs(mTransaction.getTransferAmount());
            amountText = type == ExpenseEdit.EXPENSE ? (self + " => " + other) : (other + " => " + self);
        }
    } else {
        ((TextView) mLayout.findViewById(R.id.Account)).setText(accountLabel);
        if ((mTransaction.getCatId() != null && mTransaction.getCatId() > 0)) {
            ((TextView) mLayout.findViewById(R.id.Category)).setText(mTransaction.label);
        } else {
            mLayout.findViewById(R.id.CategoryRow).setVisibility(View.GONE);
        }
        amountText = formatCurrencyAbs(mTransaction.getAmount());
    }

    //noinspection SetTextI18n
    ((TextView) mLayout.findViewById(R.id.Date))
            .setText(DateFormat.getDateInstance(DateFormat.FULL).format(mTransaction.getDate()) + " "
                    + DateFormat.getTimeInstance(DateFormat.SHORT).format(mTransaction.getDate()));

    ((TextView) mLayout.findViewById(R.id.Amount)).setText(amountText);

    if (!mTransaction.comment.equals("")) {
        ((TextView) mLayout.findViewById(R.id.Comment)).setText(mTransaction.comment);
    } else {
        mLayout.findViewById(R.id.CommentRow).setVisibility(View.GONE);
    }

    if (!mTransaction.referenceNumber.equals("")) {
        ((TextView) mLayout.findViewById(R.id.Number)).setText(mTransaction.referenceNumber);
    } else {
        mLayout.findViewById(R.id.NumberRow).setVisibility(View.GONE);
    }

    if (!mTransaction.payee.equals("")) {
        ((TextView) mLayout.findViewById(R.id.Payee)).setText(mTransaction.payee);
        ((TextView) mLayout.findViewById(R.id.PayeeLabel)).setText(type ? R.string.payer : R.string.payee);
    } else {
        mLayout.findViewById(R.id.PayeeRow).setVisibility(View.GONE);
    }

    if (mTransaction.methodId != null) {
        ((TextView) mLayout.findViewById(R.id.Method))
                .setText(PaymentMethod.getInstanceFromDb(mTransaction.methodId).getLabel());
    } else {
        mLayout.findViewById(R.id.MethodRow).setVisibility(View.GONE);
    }

    if (Account.getInstanceFromDb(mTransaction.accountId).type.equals(AccountType.CASH)) {
        mLayout.findViewById(R.id.StatusRow).setVisibility(View.GONE);
    } else {
        TextView tv = (TextView) mLayout.findViewById(R.id.Status);
        tv.setBackgroundColor(mTransaction.crStatus.color);
        tv.setText(mTransaction.crStatus.toString());
    }

    if (mTransaction.originTemplate == null) {
        mLayout.findViewById(R.id.PlannerRow).setVisibility(View.GONE);
    } else {
        ((TextView) mLayout.findViewById(R.id.Plan))
                .setText(mTransaction.originTemplate.getPlan() == null ? getString(R.string.plan_event_deleted)
                        : Plan.prettyTimeInfo(getActivity(), mTransaction.originTemplate.getPlan().rrule,
                                mTransaction.originTemplate.getPlan().dtstart));
    }

    dlg.setTitle(title);
    if (doShowPicture) {
        ImageView image = ((ImageView) dlg.getWindow().findViewById(android.R.id.icon));
        image.setVisibility(View.VISIBLE);
        image.setScaleType(ImageView.ScaleType.CENTER_CROP);
        Picasso.with(ctx).load(mTransaction.getPictureUri()).fit().into(image);
    }
}

From source file:net.sourceforge.dvb.projectx.common.Common.java

/**
 * /*from w w w . j  ava2 s. c om*/
 */
public static String getDateAndTime() {
    return (DateFormat.getDateInstance(DateFormat.LONG).format(new Date()) + "    "
            + DateFormat.getTimeInstance(DateFormat.LONG).format(new Date()));
}

From source file:com.ehret.mixit.fragment.PeopleDetailFragment.java

private void addPeopleSession(Member membre) {
    //On recupere aussi la liste des sessions de l'utilisateur
    List<Talk> conferences = ConferenceFacade.getInstance().getSessionMembre(membre, getActivity());

    //On vide les lments
    sessionLayout.removeAllViews();//from   w ww .ja  v a 2s  . c  o m

    //On affiche les liens que si on a recuperer des choses
    if (conferences != null && !conferences.isEmpty()) {
        //On ajoute un table layout
        TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(
                TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
        TableLayout tableLayout = new TableLayout(getActivity().getBaseContext());
        tableLayout.setLayoutParams(tableParams);

        if (mInflater != null) {

            for (final Talk conf : conferences) {
                LinearLayout row = (LinearLayout) mInflater.inflate(R.layout.item_talk, tableLayout, false);
                row.setBackgroundResource(R.drawable.row_transparent_background);
                //Dans lequel nous allons ajouter le contenu que nous faisons mapp dans
                TextView horaire = (TextView) row.findViewById(R.id.talk_horaire);
                TextView talkImageText = (TextView) row.findViewById(R.id.talkImageText);
                TextView talkSalle = (TextView) row.findViewById(R.id.talk_salle);
                ImageView imageFavorite = (ImageView) row.findViewById(R.id.talk_image_favorite);
                ImageView langImage = (ImageView) row.findViewById(R.id.talk_image_language);

                ((TextView) row.findViewById(R.id.talk_name)).setText(conf.getTitle());
                ((TextView) row.findViewById(R.id.talk_shortdesciptif)).setText(conf.getSummary().trim());

                SimpleDateFormat sdf = new SimpleDateFormat("EEE");
                if (conf.getStart() != null && conf.getEnd() != null) {
                    horaire.setText(String.format(getResources().getString(R.string.periode),
                            sdf.format(conf.getStart()),
                            DateFormat.getTimeInstance(DateFormat.SHORT).format(conf.getStart()),
                            DateFormat.getTimeInstance(DateFormat.SHORT).format(conf.getEnd())));
                } else {
                    horaire.setText(getResources().getString(R.string.pasdate));

                }
                if (conf.getLang() != null && "ENGLISH".equals(conf.getLang())) {
                    langImage.setImageDrawable(getResources().getDrawable(R.drawable.en));
                } else {
                    langImage.setImageDrawable(getResources().getDrawable(R.drawable.fr));
                }
                Salle salle = Salle.INCONNU;
                if (conf instanceof Talk && Salle.INCONNU != Salle.getSalle(conf.getRoom())) {
                    salle = Salle.getSalle(conf.getRoom());
                }
                talkSalle.setText(String.format(getResources().getString(R.string.Salle), salle.getNom()));
                talkSalle.setBackgroundColor(getResources().getColor(salle.getColor()));

                if (conf instanceof Talk) {
                    if ("Workshop".equals(((Talk) conf).getFormat())) {
                        talkImageText.setText("Atelier");
                    } else {
                        talkImageText.setText("Talk");
                    }
                } else {
                    talkImageText.setText("L.Talk");
                }

                row.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TypeFile typeFile;
                        int page = 6;
                        if (conf instanceof Talk) {
                            if ("Workshop".equals(((Talk) conf).getFormat())) {
                                typeFile = TypeFile.workshops;
                                page = 4;
                            } else {
                                typeFile = TypeFile.talks;
                                page = 3;
                            }
                        } else {
                            typeFile = TypeFile.lightningtalks;
                        }
                        ((HomeActivity) getActivity()).changeCurrentFragment(SessionDetailFragment.newInstance(
                                typeFile.toString(), conf.getIdSession(), page), typeFile.toString());
                    }
                });

                //On regarde si la conf fait partie des favoris
                SharedPreferences settings = getActivity().getSharedPreferences(UIUtils.PREFS_FAVORITES_NAME,
                        0);
                boolean trouve = false;
                for (String key : settings.getAll().keySet()) {
                    if (key.equals(String.valueOf(conf.getIdSession()))) {
                        trouve = true;
                        imageFavorite.setImageDrawable(
                                getActivity().getResources().getDrawable(R.drawable.ic_action_important));
                        break;
                    }
                }
                if (!trouve) {
                    imageFavorite.setImageDrawable(
                            getActivity().getResources().getDrawable(R.drawable.ic_action_not_important));
                }
                tableLayout.addView(row);
            }
        }
        sessionLayout.addView(tableLayout);
    } else {
        titleSessions.getLayoutParams().height = 0;
    }
}

From source file:com.nma.util.sdcardtrac.GraphFragment.java

private void drawGraph(LinearLayout view, boolean redraw) {
    float textSize, dispScale, pointSize;

    // Determine text size
    dispScale = getActivity().getResources().getDisplayMetrics().density;
    textSize = (GRAPHVIEW_TEXT_SIZE_DIP * dispScale) + 0.5f;
    pointSize = (GRAPHVIEW_POINT_SIZE_DIP * dispScale) + 0.5f;

    storageGraph = new LineGraphView(getActivity(), graphLabel);
    storageGraph.setCustomLabelFormatter(new CustomLabelFormatter() {
        String prevDate = "";

        @Override/*ww  w  .  j a  v  a  2 s  .  c om*/
        public String formatLabel(double value, boolean isValueX, int index, int lastIndex) {
            String retValue;
            boolean valueXinRange;

            valueXinRange = (index == 0) || (index == lastIndex);
            if (isValueX) { // Format time in human readable form
                if (valueXinRange) {
                    String dateStr;
                    Date currDate = new Date((long) value);

                    dateStr = DateFormat.getDateInstance(DateFormat.MEDIUM).format(currDate);

                    if (dateStr.equals(prevDate)) {
                        // Show hh:mm
                        retValue = DateFormat.getTimeInstance(DateFormat.SHORT).format(currDate);
                    } else {
                        retValue = dateStr;
                    }

                    prevDate = dateStr;
                    //Log.d(getClass().getName(), "Label is : " + retValue);
                } else {
                    retValue = " ";
                }
            } else { // Format size in human readable form
                retValue = DatabaseLoader.convertToStorageUnits(value);
                //prevDate = "";
            }
            //return super.formatLabel(value, isValueX); // let the y-value be normal-formatted
            return retValue;
        }
    });

    storageGraph.addSeries(graphSeries);
    storageGraph.setManualYAxis(true);
    storageGraph.setManualYAxisBounds(maxStorage, 0);
    storageGraph.setScalable(false);
    //storageGraph.setScrollable(true);
    storageGraph.getGraphViewStyle().setGridColor(Color.GREEN);
    storageGraph.getGraphViewStyle().setHorizontalLabelsColor(Color.YELLOW);
    storageGraph.getGraphViewStyle().setVerticalLabelsColor(Color.RED);
    storageGraph.getGraphViewStyle().setTextSize(textSize);
    storageGraph.getGraphViewStyle().setNumHorizontalLabels(2);
    storageGraph.getGraphViewStyle().setNumVerticalLabels(5);
    storageGraph.getGraphViewStyle().setVerticalLabelsWidth((int) (textSize * 4));
    //storageGraph.setMultiLineXLabel(true, ";");
    ((LineGraphView) storageGraph).setDrawBackground(true);
    ((LineGraphView) storageGraph).setDrawDataPoints(true);
    ((LineGraphView) storageGraph).setDataPointsRadius(pointSize);
    //storageGraph.highlightSample(0, true, locData.size() - 1);
    // Add selector callback
    storageGraph.setSelectHandler(this);

    setViewport(redraw);
    if (view != null) {
        view.addView(storageGraph);
    }
    if (SettingsActivity.ENABLE_DEBUG)
        Log.d(getClass().getName(), "Drew the graph, redraw=" + redraw);
}

From source file:com.appeligo.showfiles.ShowFile.java

/**
 * @param request//  w  w w .  j  ava 2s . c  o  m
 * @param out
 * @param path
 * @param f
 */
private void listFiles(HttpServletRequest request, PrintWriter out, String path, File f) {
    header(out, path);
    String[] filenames = f.list();
    Arrays.sort(filenames);
    for (int i = 0; i < filenames.length; i++) {
        String filename = filenames[i];
        String fullPathname = documentRoot + path + "/" + filename;
        File child = new File(fullPathname);
        if (child.isHidden()) {
            continue;
        }
        if (filename.endsWith(".flv")) {
            if (new File(fullPathname.replace(".flv", ".html.gz")).exists()) {
                continue;
            }
        }
        filename = filename.replace(":", "%3a");
        if (!path.endsWith("/")) {
            path = path + "/";
        }
        String displayName = filenames[i];
        if (child.isDirectory()) {
            displayName += "/";
            if (!filename.endsWith("/")) {
                filename = filename + "/";
            }
        }
        if (filename.endsWith(".html.gz")) {
            if (new File(fullPathname.replace(".html.gz", ".flv")).exists()) {
                out.println("<a href=\"" + request.getContextPath() + "/ShowFlv" +
                //request.getServletPath()+
                        path + filename.replace(".html.gz", ".flv") + "\">" + "<img src=\""
                        + request.getContextPath() + "/skins/default/videoIcon.gif\" alt=\"video\"/>" + "</a>");
            }
            String tsString = filename.substring(0, filename.indexOf('.'));
            try {
                long timestamp = Long.parseLong(tsString);
                DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT);
                df.setTimeZone(TimeZone.getTimeZone("GMT"));
                String time = df.format(new Date(timestamp)) + " - ";
                if (time.indexOf(':') == 1) {
                    time = "0" + time;
                }
                out.print(time);
            } catch (NumberFormatException e) {
            }
        } else if (filename.endsWith(".flv") && (filename.indexOf(",") > 0)) {
            showPreview(request, out, path, filename);
        }
        out.print("<a href=\"" + request.getContextPath() + request.getServletPath() + path + filename + "\">"
                + displayName + "</a>");
        if (filename.endsWith(".html.gz")) {
            BufferedReader r;
            try {
                r = new BufferedReader(
                        new InputStreamReader(new GZIPInputStream(new FileInputStream(fullPathname))));
                String line;
                while ((line = r.readLine()) != null) {
                    if (line.startsWith("<title>")) {
                        int nextLT = line.indexOf('<', 7);
                        String title = line.substring(7, nextLT);
                        out.print(" " + title);
                        break;
                    }
                }
                r.close();
            } catch (FileNotFoundException e) {
            } catch (IOException e) {
            }
        }
        out.println("<br/>");
    }
    footer(out);
}

From source file:de.dreier.mytargets.features.statistics.StatisticsFragment.java

@NonNull
private Evaluator getEntryEvaluator(final List<Pair<Float, DateTime>> values) {
    boolean singleTraining = Stream.of(rounds).groupBy(r -> r.trainingId).count() == 1;

    Evaluator eval;/*from   w  ww  .  j ava 2 s . com*/
    if (singleTraining) {
        eval = new Evaluator() {
            private DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT);

            @Override
            public long getXValue(List<Pair<Float, DateTime>> values, int i) {
                return values.get(i).second.getMillis() - values.get(0).second.getMillis();
            }

            @Override
            public String getXValueFormatted(float value) {
                final long diffToFirst = (long) value;
                return dateFormat.format(new Date(values.get(0).second.getMillis() + diffToFirst));
            }
        };
    } else {
        eval = new Evaluator() {
            private DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);

            @Override
            public long getXValue(List<Pair<Float, DateTime>> values, int i) {
                return i;
            }

            @Override
            public String getXValueFormatted(float value) {
                return dateFormat.format(values.get((int) value).second.toDate());
            }
        };
    }
    return eval;
}

From source file:org.svij.taskwarriorapp.activities.TaskAddActivity.java

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    if (savedInstanceState != null) {
        timestamp = savedInstanceState.getLong("timestamp");

        if (timestamp != 0) {
            cal.setTimeInMillis(timestamp);

            TextView tvDueTime = (TextView) findViewById(R.id.tvDueTime);
            tvDueTime.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(timestamp));
            TextView tvDueDate = (TextView) findViewById(R.id.tvDueDate);
            tvDueDate.setText(DateFormat.getDateInstance(DateFormat.SHORT).format(timestamp));
        }//  www. j  a  va2  s . c o  m
    }
}