Example usage for android.text.format DateUtils formatDateTime

List of usage examples for android.text.format DateUtils formatDateTime

Introduction

In this page you can find the example usage for android.text.format DateUtils formatDateTime.

Prototype

public static String formatDateTime(Context context, long millis, int flags) 

Source Link

Document

Formats a date or a time according to the local conventions.

Usage

From source file:Main.java

public static String formatDateTime(Context context, long time) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
    Date d = new Date(time);
    int currentYear = Calendar.getInstance().get(Calendar.YEAR);
    int year = Integer.parseInt(TextUtils.isDigitsOnly(sdf.format(d)) ? sdf.format(d) : currentYear + "");
    if (currentYear == year) {
        return DateUtils.formatDateTime(context, time, DateUtils.FORMAT_SHOW_DATE
                //| DateUtils.FORMAT_SHOW_WEEKDAY
                //| DateUtils.FORMAT_SHOW_YEAR
                | DateUtils.FORMAT_ABBREV_MONTH
                //| DateUtils.FORMAT_ABBREV_WEEKDAY
                | DateUtils.FORMAT_ABBREV_TIME | DateUtils.FORMAT_SHOW_TIME);
    } else {/*from w w w  .  j a  v  a  2  s  .com*/
        return DateUtils.formatDateTime(context, time, DateUtils.FORMAT_SHOW_DATE
                //| DateUtils.FORMAT_SHOW_WEEKDAY
                | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_ABBREV_MONTH
                //| DateUtils.FORMAT_ABBREV_WEEKDAY
                | DateUtils.FORMAT_ABBREV_TIME | DateUtils.FORMAT_SHOW_TIME);
    }

}

From source file:Main.java

/**
 * Returns a date string in the format specified, which shows an abbreviated date without a
 * year./*from  w w w .  j a  v  a2  s. c o  m*/
 *
 * @param context      Used by DateUtils to format the date in the current locale
 * @param timeInMillis Time in milliseconds since the epoch (local time)
 *
 * @return The formatted date string
 */
private static String getReadableDateString(Context context, long timeInMillis) {
    int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR | DateUtils.FORMAT_SHOW_WEEKDAY;

    return DateUtils.formatDateTime(context, timeInMillis, flags);
}

From source file:Main.java

@SuppressWarnings("deprecation")
public static String formatTimeStampString(Context context, long when, boolean fullFormat) {
    Time then = new Time();
    then.set(when);//from  w ww  . j  a v  a 2 s  .c o m

    Time now = new Time();
    now.setToNow();

    // Basic settings for formatDateTime() we want for all cases.
    int format_flags = DateUtils.FORMAT_NO_NOON_MIDNIGHT | DateUtils.FORMAT_ABBREV_ALL
            | DateUtils.FORMAT_CAP_AMPM;

    // If the message is from a different year, show the date and year.
    if (then.year != now.year) {
        format_flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
    } else if (then.yearDay != now.yearDay) {
        // If it is from a different day than today, show only the date.
        format_flags |= DateUtils.FORMAT_SHOW_DATE;
    } else {
        // Otherwise, if the message is from today, show the time.
        format_flags |= DateUtils.FORMAT_SHOW_TIME;
    }

    // If the caller has asked for full details, make sure to show the date
    // and time no matter what we've determined above (but still make
    // showing
    // the year only happen if it is a different year from today).
    if (fullFormat) {
        format_flags |= (DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);
    }

    return DateUtils.formatDateTime(context, when, format_flags);
}

From source file:Main.java

public static void setTime(Activity activity, TextView view, long millis) {
    int flags = DateUtils.FORMAT_SHOW_TIME;
    flags |= DateUtils.FORMAT_CAP_NOON_MIDNIGHT;
    if (DateFormat.is24HourFormat(activity)) {
        flags |= DateUtils.FORMAT_24HOUR;
    }//from   w  w  w . j  a va  2 s .co  m

    // Unfortunately, DateUtils doesn't support a timezone other than the
    // default timezone provided by the system, so we have this ugly hack
    // here to trick it into formatting our time correctly. In order to
    // prevent all sorts of craziness, we synchronize on the TimeZone class
    // to prevent other threads from reading an incorrect timezone from
    // calls to TimeZone#getDefault()
    // TODO fix this if/when DateUtils allows for passing in a timezone
    String timeString;
    synchronized (TimeZone.class) {
        timeString = DateUtils.formatDateTime(activity, millis, flags);
        TimeZone.setDefault(null);
    }

    view.setTag(millis);
    view.setText(timeString);
}

From source file:de.incoherent.suseconferenceclient.app.SocialWrapper.java

public static ArrayList<SocialItem> getTwitterItems(Context context, String tag, int maximum) {
    String twitterSearch = "http://search.twitter.com/search.json?q=" + tag;
    ArrayList<SocialItem> socialItems = new ArrayList<SocialItem>();

    // TODO Android 2.2 thinks that "Wed, 19 Sep 2012 16:35:43 +0000" is invalid
    // with this formatter
    SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    try {/*from   w ww  . java2s . co  m*/
        Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.twitter_icon);
        JSONObject result = HTTPWrapper.get(twitterSearch);
        JSONArray items = result.getJSONArray("results");
        int len = items.length();
        if ((len > 0) && (maximum > 0) && (len > maximum))
            len = maximum;

        for (int i = 0; i < len; i++) {
            JSONObject jsonItem = items.getJSONObject(i);
            Bitmap image = HTTPWrapper.getImage(jsonItem.getString("profile_image_url"));
            Date formattedDate = new Date();
            try {
                formattedDate = formatter.parse(jsonItem.getString("created_at"));
            } catch (ParseException e) {
                Log.d("SUSEConferences", "Invalid date string: " + jsonItem.getString("created_at"));
                e.printStackTrace();
            }
            String user = jsonItem.getString("from_user");
            SocialItem newItem = new SocialItem(SocialItem.TWITTER, user, jsonItem.getString("text"),
                    formattedDate,
                    DateUtils
                            .formatDateTime(context, formattedDate.getTime(),
                                    DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_NUMERIC_DATE
                                            | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE),
                    image, icon);
            String link = "http://twitter.com/" + user + "/status/" + jsonItem.getString("id_str");
            newItem.setLink(link);
            socialItems.add(newItem);
        }
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return socialItems;
}

From source file:nl.atcomputing.spacetravelagency.order.DepartureInfoService.java

private void sendNotification(long epochInMilliseconds) {

    /*// w w w.jav a2  s.co m
     * Unclear what should replace it. Official docs do not mention FORMAT_24HOUR as deprecated
     */
    @SuppressWarnings("deprecation")
    CharSequence dateString = DateUtils.formatDateTime(this, epochInMilliseconds,
            DateUtils.FORMAT_24HOUR | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);

    Intent intent = new Intent(this, PlaceOrderActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);

    NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    @SuppressWarnings("deprecation")
    Notification notification = builder.setContentIntent(pi).setSmallIcon(R.drawable.ic_notification_icon)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.spaceship_launcher))
            .setTicker(getString(R.string.departure_time_changed)).setWhen(System.currentTimeMillis())
            .setAutoCancel(true).setContentTitle(getString(R.string.app_name))
            .setContentText(getString(R.string.departure_time_changed_to_) + dateString).getNotification();

    nm.notify(1, notification);
}

From source file:com.commonsware.android.debug.webserver.PicassoDiagnosticService.java

@Override
protected Context getContextForPath(String relpath) {
    if ("picasso.hbs".equals(relpath)) {
        StatsSnapshot ss = Picasso.with(PicassoDiagnosticService.this).getSnapshot();
        String formattedTime = DateUtils.formatDateTime(PicassoDiagnosticService.this, ss.timeStamp,
                DateUtils.FORMAT_SHOW_TIME);

        return (Context.newBuilder(ss).combine("formattedTime", formattedTime)
                .resolver(FieldValueResolver.INSTANCE).build());
    }/*  ww  w . ja va2s. c om*/

    throw new IllegalStateException("Did not recognize " + relpath);
}

From source file:org.dronix.android.unisannio.fragment.TabOne.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tabone, container, false);
    mPullRefreshListView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list);

    // Set a listener to be invoked when the list should be refreshed.
    mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
        @Override//  w w w .  j a v  a  2 s.  com
        public void onRefresh(PullToRefreshBase<ListView> refreshView) {
            mPullRefreshListView.setLastUpdatedLabel(DateUtils.formatDateTime(getActivity(),
                    System.currentTimeMillis(),
                    DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL));

            new NewsRetriever().execute();
        }
    });

    ListView actualListView = mPullRefreshListView.getRefreshableView();

    news = new ArrayList<News>();
    news.add(new News("", getString(R.string.pull)));

    mAdapter = new LazyAdapter(getActivity(), news);

    actualListView.setAdapter(mAdapter);
    return view;
}

From source file:ca.rmen.android.poetassistant.wotd.WotdLoader.java

@Override
public ResultListData<WotdEntry> loadInBackground() {
    Log.d(TAG, "loadInBackground()");

    List<WotdEntry> data = new ArrayList<>(100);

    Cursor cursor = mDictionary.getRandomWordCursor();
    if (cursor == null || cursor.getCount() == 0)
        return emptyResult();

    try {/*from www. j a  v  a  2 s .c  om*/
        Set<String> favorites = mFavorites.getFavorites();
        Calendar calendar = Wotd.getTodayUTC();
        Calendar calendarDisplay = Wotd.getTodayUTC();
        calendarDisplay.setTimeZone(TimeZone.getDefault());
        Settings.Layout layout = Settings.getLayout(mPrefs);
        for (int i = 0; i < 100; i++) {
            Random random = new Random();
            random.setSeed(calendar.getTimeInMillis());
            String date = DateUtils.formatDateTime(getContext(), calendarDisplay.getTimeInMillis(),
                    DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            int position = random.nextInt(cursor.getCount());
            if (cursor.moveToPosition(position)) {
                String word = cursor.getString(0);
                @ColorRes
                int color = (i % 2 == 0) ? R.color.row_background_color_even : R.color.row_background_color_odd;
                data.add(new WotdEntry(word, date, ContextCompat.getColor(getContext(), color),
                        favorites.contains(word), layout == Settings.Layout.EFFICIENT));
            }
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            calendarDisplay.add(Calendar.DAY_OF_YEAR, -1);

        }

    } finally {
        cursor.close();
    }
    return new ResultListData<>(getContext().getString(R.string.wotd_list_header), false, data);
}

From source file:org.dronix.android.unisannio.fragment.AvvisiIngFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tabone, container, false);

    TextView title = (TextView) view.findViewById(R.id.title);
    title.setText(getString(R.string.avvisi_ingengeria));

    mPullRefreshListView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list);

    // Set a listener to be invoked when the list should be refreshed.
    mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
        @Override/*from  w  ww . j a v a 2s.  c om*/
        public void onRefresh(PullToRefreshBase<ListView> refreshView) {
            mPullRefreshListView.setLastUpdatedLabel(DateUtils.formatDateTime(getActivity(),
                    System.currentTimeMillis(),
                    DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL));

            new NewsRetriever().execute();
        }
    });

    ListView actualListView = mPullRefreshListView.getRefreshableView();

    news = new ArrayList<NewsIng>();
    news.add(new NewsIng(getString(R.string.pull), "", null, null, ""));

    mAdapter = new NewsIngAdapter(getActivity(), news);

    actualListView.setAdapter(mAdapter);

    actualListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent i = new Intent(getActivity(), NewsDetailActivity.class);
            i.putExtra("newsing", news.get(--position));
            startActivity(i);
        }
    });

    return view;
}