Java Code Examples for android.text.format.DateUtils#formatDateTime()

The following examples show how to use android.text.format.DateUtils#formatDateTime() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AppCompatDatePickerDelegate.java    From AppCompat-Extension-Library with Apache License 2.0 6 votes vote down vote up
private void onCurrentDateChanged(boolean announce) {
    if (mHeaderYear == null) {
        // Abort, we haven't initialized yet. This method will get called
        // again later after everything has been set up.
        return;
    }

    final String year = mYearFormat.format(mCurrentDate.getTime());
    mHeaderYear.setText(year);

    final String monthDay = DateFormatUtils.format(mMonthDayFormat, mCurrentDate);
    mHeaderMonthDay.setText(monthDay);

    // TODO: This should use live regions.
    if (announce) {
        final long millis = mCurrentDate.getTimeInMillis();
        final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
        final String fullDateText = DateUtils.formatDateTime(mContext, millis, flags);
        ViewCompatUtils.announceForAccessibility(mAnimator, fullDateText);
    }
}
 
Example 2
Source File: RadialPickerLayout.java    From Android-SwitchDateTimePicker with Apache License 2.0 6 votes vote down vote up
/**
 * Announce the currently-selected time when launched.
 */
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
    if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
        // Clear the event's current text so that only the current time will be spoken.
        event.getText().clear();
        Time time = new Time();
        time.hour = getHours();
        time.minute = getMinutes();
        long millis = time.normalize(true);
        int flags = DateUtils.FORMAT_SHOW_TIME;
        if (mIs24HourMode) {
            flags |= DateUtils.FORMAT_24HOUR;
        }
        String timeString = DateUtils.formatDateTime(getContext(), millis, flags);
        event.getText().add(timeString);
        return true;
    }
    return super.dispatchPopulateAccessibilityEvent(event);
}
 
Example 3
Source File: PhoneMainActivity.java    From wear-os-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    // the following if-clause is to get around a bug that causes this callback to be called
    // twice
    if (view.isShown()) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, monthOfYear);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        String date = DateUtils.formatDateTime(this, calendar.getTimeInMillis(),
                DateUtils.FORMAT_SHOW_DATE);
        mSelectedDateText.setText(getString(R.string.showing_for_date, date));
        showTrack(calendar);
    }
}
 
Example 4
Source File: TimeCounterListAdapter.java    From DoraemonKit with Apache License 2.0 6 votes vote down vote up
@Override
public void bind(final CounterInfo info, int position) {
    tvTitle.setText(info.title);
    String time = DateUtils.formatDateTime(getContext(),
            info.time, FORMAT_SHOW_TIME);
    tvTime.setText(time);
    setTotalCost(info.totalCost);
    itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            info.show = !info.show;
            showDetail(info);
            if (info.type == CounterInfo.TYPE_APP && mContext != null) {
                //跳转启动耗时详情页
                Intent intent = new Intent(mContext, UniversalActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(BundleKey.FRAGMENT_INDEX, FragmentIndex.FRAGMENT_APP_START);
                mContext.startActivity(intent);
            }
        }
    });
    showDetail(info);
}
 
Example 5
Source File: RadialPickerLayout.java    From AlarmOn with Apache License 2.0 6 votes vote down vote up
/**
 * Announce the currently-selected time when launched.
 */
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
    if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
        // Clear the event's current text so that only the current time will be spoken.
        event.getText().clear();
        Calendar time = Calendar.getInstance();
        time.set(Calendar.HOUR, getHours());
        time.set(Calendar.MINUTE, getMinutes());
        time.set(Calendar.SECOND, getSeconds());
        long millis = time.getTimeInMillis();
        int flags = DateUtils.FORMAT_SHOW_TIME;
        if (mIs24HourMode) {
            flags |= DateUtils.FORMAT_24HOUR;
        }
        String timeString = DateUtils.formatDateTime(getContext(), millis, flags);
        event.getText().add(timeString);
        return true;
    }
    return super.dispatchPopulateAccessibilityEvent(event);
}
 
Example 6
Source File: TimePicker.java    From NewXmPluginSDK with Apache License 2.0 6 votes vote down vote up
@Override
public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
    super.onPopulateAccessibilityEvent(event);

    int flags = DateUtils.FORMAT_SHOW_TIME;
    if (mIs24HourView) {
        flags |= DateUtils.FORMAT_24HOUR;
    } else {
        flags |= DateUtils.FORMAT_12HOUR;
    }
    mTempCalendar.set(Calendar.HOUR_OF_DAY, getCurrentHour());
    mTempCalendar.set(Calendar.MINUTE, getCurrentMinute());
    String selectedDateUtterance = DateUtils.formatDateTime(getContext(),
            mTempCalendar.getTimeInMillis(), flags);
    event.getText().add(selectedDateUtterance);
}
 
Example 7
Source File: TwoFieldDatePicker.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
    super.onPopulateAccessibilityEvent(event);

    final int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
    String selectedDateUtterance = DateUtils.formatDateTime(getContext(),
            mCurrentDate.getTimeInMillis(), flags);
    event.getText().add(selectedDateUtterance);
}
 
Example 8
Source File: BeerRatingsAdapter.java    From ratebeer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
	BeerRating rating = ratings.get(position);
	Images.with(holder.avatarImage.getContext()).loadUser(rating.userName).placeholder(android.R.color.white).fit().centerCrop()
			.into(holder.avatarImage);
	if (rating.timeEntered == null) {
		// Directly show comments
		holder.ratingCommentsText.setText(asHtml(rating.comments));
	} else {
		// Show comments and (in grey) the rating date
		Context context = holder.ratingCommentsText.getContext();
		String timeEnteredText = DateUtils.formatDateTime(context, rating.timeEntered.getTime(),
				DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_NUMERIC_DATE);
		SpannableStringBuilder commentsMarkup = new SpannableStringBuilder(asHtml(rating.comments));
		commentsMarkup.append(" ");
		commentsMarkup.append(timeEnteredText);
		commentsMarkup.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.grey_light)),
				commentsMarkup.length() - timeEnteredText.length(), commentsMarkup.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		commentsMarkup.setSpan(new RelativeSizeSpan(0.8F), commentsMarkup.length() - timeEnteredText.length(), commentsMarkup.length(),
				Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		holder.ratingCommentsText.setText(commentsMarkup);
	}
	holder.ratingMarkText.setBackgroundResource(ImageUrls.getColor(position, true));
	holder.userNameText.setText(rating.userName);
	holder.userCountText.setText(String.format(Locale.getDefault(), "%1$d", rating.userRateCount));
	if (rating.timeEntered == null) {
		holder.offlineBadge.setVisibility(View.VISIBLE);
		holder.userCountryText.setVisibility(View.GONE);
		holder.ratingMarkText.setText("-");
	} else {
		holder.offlineBadge.setVisibility(View.GONE);
		holder.userCountryText.setVisibility(View.VISIBLE);
		holder.userCountryText.setText(rating.userCountryName);
		holder.ratingMarkText.setText(String.format(Locale.getDefault(), "%1$.1f", rating.total));
	}
}
 
Example 9
Source File: DateSpinner.java    From ReminderDatePicker with Apache License 2.0 5 votes vote down vote up
private String formatSecondaryDate(@NonNull Calendar date) {
    if(secondaryDateFormat == null)
        return DateUtils.formatDateTime(getContext(), date.getTimeInMillis(),
                DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NUMERIC_DATE);
    else
        return secondaryDateFormat.format(date.getTime());
}
 
Example 10
Source File: DatePickerDialog.java    From DateTimepicker with Apache License 2.0 5 votes vote down vote up
private void updateDisplay() {  
	if (this.mDayOfWeekView != null){
		this.mCalendar.setFirstDayOfWeek(mWeekStart);
		this.mDayOfWeekView.setText(dateformartsymbols.getWeekdays()[this.mCalendar.get(Calendar.DAY_OF_WEEK)].toUpperCase(Locale.getDefault()));
	}
		
	this.mSelectedMonthTextView.setText(dateformartsymbols.getMonths()[this.mCalendar.get(Calendar.MONTH)].toUpperCase(Locale.getDefault()));
	this.mSelectedDayTextView.setText(DAY_FORMAT.format(this.mCalendar.getTime()));
	this.mYearView.setText(YEAR_FORMAT.format(this.mCalendar.getTime()));
	long timeInMillis = this.mCalendar.getTimeInMillis();
	String desc = DateUtils.formatDateTime(getActivity(), timeInMillis, 24);
	this.mMonthAndDayView.setContentDescription(desc);
}
 
Example 11
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method to convert the database representation of the date into something to display
 * to users.  As classy and polished a user experience as "20140102" is, we can do better.
 * <p/>
 * The day string for forecast uses the following logic:
 * For today: "Today, June 8"
 * For tomorrow:  "Tomorrow"
 * For the next 5 days: "Wednesday" (just the day name)
 * For all days after that: "Mon, Jun 8" (Mon, 8 Jun in UK, for example)
 *
 * @param context      Context to use for resource localization
 * @param dateInMillis The date in milliseconds (UTC)
 * @param showFullDate Used to show a fuller-version of the date, which always contains either
 *                     the day of the week, today, or tomorrow, in addition to the date.
 *
 * @return A user-friendly representation of the date such as "Today, June 8", "Tomorrow",
 * or "Friday"
 */
public static String getFriendlyDateString(Context context, long dateInMillis, boolean showFullDate) {

    long localDate = getLocalDateFromUTC(dateInMillis);
    long dayNumber = getDayNumber(localDate);
    long currentDayNumber = getDayNumber(System.currentTimeMillis());

    if (dayNumber == currentDayNumber || showFullDate) {
        /*
         * If the date we're building the String for is today's date, the format
         * is "Today, June 24"
         */
        String dayName = getDayName(context, localDate);
        String readableDate = getReadableDateString(context, localDate);
        if (dayNumber - currentDayNumber < 2) {
            /*
             * Since there is no localized format that returns "Today" or "Tomorrow" in the API
             * levels we have to support, we take the name of the day (from SimpleDateFormat)
             * and use it to replace the date from DateUtils. This isn't guaranteed to work,
             * but our testing so far has been conclusively positive.
             *
             * For information on a simpler API to use (on API > 18), please check out the
             * documentation on DateFormat#getBestDateTimePattern(Locale, String)
             * https://developer.android.com/reference/android/text/format/DateFormat.html#getBestDateTimePattern
             */
            String localizedDayName = new SimpleDateFormat("EEEE").format(localDate);
            return readableDate.replace(localizedDayName, dayName);
        } else {
            return readableDate;
        }
    } else if (dayNumber < currentDayNumber + 7) {
        /* If the input date is less than a week in the future, just return the day name. */
        return getDayName(context, localDate);
    } else {
        int flags = DateUtils.FORMAT_SHOW_DATE
                | DateUtils.FORMAT_NO_YEAR
                | DateUtils.FORMAT_ABBREV_ALL
                | DateUtils.FORMAT_SHOW_WEEKDAY;

        return DateUtils.formatDateTime(context, localDate, flags);
    }
}
 
Example 12
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method to convert the database representation of the date into something to display
 * to users.  As classy and polished a user experience as "20140102" is, we can do better.
 * <p/>
 * The day string for forecast uses the following logic:
 * For today: "Today, June 8"
 * For tomorrow:  "Tomorrow"
 * For the next 5 days: "Wednesday" (just the day name)
 * For all days after that: "Mon, Jun 8" (Mon, 8 Jun in UK, for example)
 *
 * @param context      Context to use for resource localization
 * @param dateInMillis The date in milliseconds (UTC)
 * @param showFullDate Used to show a fuller-version of the date, which always contains either
 *                     the day of the week, today, or tomorrow, in addition to the date.
 *
 * @return A user-friendly representation of the date such as "Today, June 8", "Tomorrow",
 * or "Friday"
 */
public static String getFriendlyDateString(Context context, long dateInMillis, boolean showFullDate) {

    long localDate = getLocalDateFromUTC(dateInMillis);
    long dayNumber = getDayNumber(localDate);
    long currentDayNumber = getDayNumber(System.currentTimeMillis());

    if (dayNumber == currentDayNumber || showFullDate) {
        /*
         * If the date we're building the String for is today's date, the format
         * is "Today, June 24"
         */
        String dayName = getDayName(context, localDate);
        String readableDate = getReadableDateString(context, localDate);
        if (dayNumber - currentDayNumber < 2) {
            /*
             * Since there is no localized format that returns "Today" or "Tomorrow" in the API
             * levels we have to support, we take the name of the day (from SimpleDateFormat)
             * and use it to replace the date from DateUtils. This isn't guaranteed to work,
             * but our testing so far has been conclusively positive.
             *
             * For information on a simpler API to use (on API > 18), please check out the
             * documentation on DateFormat#getBestDateTimePattern(Locale, String)
             * https://developer.android.com/reference/android/text/format/DateFormat.html#getBestDateTimePattern
             */
            String localizedDayName = new SimpleDateFormat("EEEE").format(localDate);
            return readableDate.replace(localizedDayName, dayName);
        } else {
            return readableDate;
        }
    } else if (dayNumber < currentDayNumber + 7) {
        /* If the input date is less than a week in the future, just return the day name. */
        return getDayName(context, localDate);
    } else {
        int flags = DateUtils.FORMAT_SHOW_DATE
                | DateUtils.FORMAT_NO_YEAR
                | DateUtils.FORMAT_ABBREV_ALL
                | DateUtils.FORMAT_SHOW_WEEKDAY;

        return DateUtils.formatDateTime(context, localDate, flags);
    }
}
 
Example 13
Source File: AnalogClock.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private void updateContentDescription(Time time) {
    final int flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_24HOUR;
    String contentDescription = DateUtils.formatDateTime(mContext,
            time.toMillis(false), flags);
    setContentDescription(contentDescription);
}
 
Example 14
Source File: ChatMessagesAdapter.java    From revolution-irc with GNU General Public License v3.0 4 votes vote down vote up
public String getMessageText(Context ctx) {
    return DateUtils.formatDateTime(ctx, getDateIntMs(mDate), DateUtils.FORMAT_SHOW_DATE);
}
 
Example 15
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 4 votes vote down vote up
/**
 * Helper method to convert the database representation of the date into something to display
 * to users.  As classy and polished a user experience as "20140102" is, we can do better.
 * <p/>
 * The day string for forecast uses the following logic:
 * For today: "Today, June 8"
 * For tomorrow:  "Tomorrow"
 * For the next 5 days: "Wednesday" (just the day name)
 * For all days after that: "Mon, Jun 8" (Mon, 8 Jun in UK, for example)
 *
 * @param context      Context to use for resource localization
 * @param dateInMillis The date in milliseconds (UTC)
 * @param showFullDate Used to show a fuller-version of the date, which always contains either
 *                     the day of the week, today, or tomorrow, in addition to the date.
 *
 * @return A user-friendly representation of the date such as "Today, June 8", "Tomorrow",
 * or "Friday"
 */
public static String getFriendlyDateString(Context context, long dateInMillis, boolean showFullDate) {

    long localDate = getLocalDateFromUTC(dateInMillis);
    long dayNumber = getDayNumber(localDate);
    long currentDayNumber = getDayNumber(System.currentTimeMillis());

    if (dayNumber == currentDayNumber || showFullDate) {
        /*
         * If the date we're building the String for is today's date, the format
         * is "Today, June 24"
         */
        String dayName = getDayName(context, localDate);
        String readableDate = getReadableDateString(context, localDate);
        if (dayNumber - currentDayNumber < 2) {
            /*
             * Since there is no localized format that returns "Today" or "Tomorrow" in the API
             * levels we have to support, we take the name of the day (from SimpleDateFormat)
             * and use it to replace the date from DateUtils. This isn't guaranteed to work,
             * but our testing so far has been conclusively positive.
             *
             * For information on a simpler API to use (on API > 18), please check out the
             * documentation on DateFormat#getBestDateTimePattern(Locale, String)
             * https://developer.android.com/reference/android/text/format/DateFormat.html#getBestDateTimePattern
             */
            String localizedDayName = new SimpleDateFormat("EEEE").format(localDate);
            return readableDate.replace(localizedDayName, dayName);
        } else {
            return readableDate;
        }
    } else if (dayNumber < currentDayNumber + 7) {
        /* If the input date is less than a week in the future, just return the day name. */
        return getDayName(context, localDate);
    } else {
        int flags = DateUtils.FORMAT_SHOW_DATE
                | DateUtils.FORMAT_NO_YEAR
                | DateUtils.FORMAT_ABBREV_ALL
                | DateUtils.FORMAT_SHOW_WEEKDAY;

        return DateUtils.formatDateTime(context, localDate, flags);
    }
}
 
Example 16
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a date string in the format specified, which shows an abbreviated date without a
 * year.
 *
 * @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);
}
 
Example 17
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a date string in the format specified, which shows an abbreviated date without a
 * year.
 *
 * @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);
}
 
Example 18
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a date string in the format specified, which shows an abbreviated date without a
 * year.
 *
 * @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);
}
 
Example 19
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a date string in the format specified, which shows a date, without a year,
 * abbreviated, showing the full weekday.
 *
 * @param context      Used by DateUtils to formate 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);
}
 
Example 20
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a date string in the format specified, which shows a date, without a year,
 * abbreviated, showing the full weekday.
 *
 * @param context      Used by DateUtils to formate 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);
}