Java 类android.text.format.DateUtils 实例源码

项目:OpenHomeAnalysis    文件:OhaEnergyUseLogTask.java   
/**
 * Recuperar os logs de utilização de energia.
 * @param hostName informar o enderço do Registrador na rede.
 * @param strDate informar uma data válida.
 * @param strHour informar uma hora válida.
 * @param startSequence informar a ultima sequencia importada.
 * @return uma lista com conteúdo de {@link OhaEnergyUseLog} ou {@link OhaStatusLog}
 * @throws ParseException se não for possível converter o parâmetro strDate em uma data válida.
 * @throws IOException se o Registrador de Utilização de Energia não for localizado na Rede.
 * @throws EnergyUseLogRead se ocorrer erro na leitura dos logs.
 * @throws EnergyUseLogSdCardFatalError se ocorrer qualquer problema no SD Card do Registrador.
 * @throws EnergyUseRequestTimeOut se ocorrer problema de comunicação entre o Registrador(Arduino) e o Módulo WiFi(ESP8266).
 * @throws InterruptedException se ocorrer erro na requisição de delay.
 */
private List<String> getLogs(String hostName, String strDate, String strHour, int startSequence)
        throws
        ParseException,
        IOException,
        EnergyUseLogRead,
        EnergyUseLogSdCardFatalError,
        EnergyUseRequestTimeOut,
        InterruptedException,
        BackupAndRestoreOperation{
    //Definir a data de exclusão dos logs para liberar espaço no
    //SD Card do Registrador de Utilização de Energia considerando a preferência do usuário:
    Calendar calendar = OhaHelper.getCalendar(strDate);
    calendar.add(Calendar.DATE, ohaEnergyUseSyncHelper.getDaysSdCardStored() * -1);
    String strDateLogDelete = OhaHelper.getStrDate(calendar.getTime());
    //Realizar as tentativas:
    List<String> strings = new ArrayList<>();
    for (int tryCount = 1; tryCount <= NUMBER_ATTEMPTS; tryCount++) {
        strings = OhaEnergyUseApi.getLogs(hostName, strDate, strHour, startSequence, 25, strDateLogDelete);
        //Verificar se o status retornado é válido:
        assertOhaStatusLog(strings, tryCount);
        if (OhaStatusLog.exists(OhaStatusLog.OHA_REQUEST_END, strings)) {
            break;
        }
        //Executar um delay e tentar novamente:
        delay(DateUtils.SECOND_IN_MILLIS * 10);
    }
    //Se existir somente o status OHA_REQUEST_END, a lista não tem conteúdo de logs e está vazia!
    if ( strings.size() < 1){
        new EnergyUseLogRead(String.format("getLogs on %s, %s and %s is empty!", strDate, strHour, startSequence));
    }
    return strings;
}
项目:OpenHomeAnalysis    文件:OhaEnergyUseLogTask.java   
/**
 * Atualizar a próxima sequencia de importação dos logs nas preferências de sincronização.
 * @throws ParseException se não for possível converter o parâmetro strDate em uma data válida.
 * @throws EnergyUseLogSyncFatalError se a data e hora informada for maior do que a data e hora atual.
 */
private void setNextOhaSequenceLog()
        throws
        ParseException,
        EnergyUseLogSyncFatalError {
    Calendar calendar = OhaHelper.getCalendar(ohaEnergyUseSyncHelper.getStrDate(), ohaEnergyUseSyncHelper.getStrHour());
    calendar.add(Calendar.HOUR, 1);
    //A data e hora de importação não pode ser maior do que a data e hora atual:
    if (calendar.getTime().after (new Date())) {
        delay(DateUtils.MINUTE_IN_MILLIS);
        return;
    }
    ohaEnergyUseSyncHelper.setDate(OhaHelper.getStrDate(calendar.getTime()));
    ohaEnergyUseSyncHelper.setHour(OhaHelper.getStrHour(calendar.getTime()));
    ohaEnergyUseSyncHelper.setSequence(1);
}
项目:OSchina_resources_android    文件:AccessibleDateAnimator.java   
/**
 * Announce the currently-selected date 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 date will
        // be spoken.
        event.getText().clear();
        int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR
                | DateUtils.FORMAT_SHOW_WEEKDAY;

        String dateString = DateUtils.formatDateTime(getContext(),
                mDateMillis, flags);
        event.getText().add(dateString);
        return true;
    }
    return super.dispatchPopulateAccessibilityEvent(event);
}
项目:q-mail    文件:FolderList.java   
private String buildFolderStatus(FolderInfoHolder folder) {
    String folderStatus;
    if (folder.loading) {
        folderStatus = getString(R.string.status_loading);
    } else if (folder.status != null) {
        folderStatus = folder.status;
    } else if (folder.lastChecked != 0) {
        long now = System.currentTimeMillis();
        int flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
        CharSequence formattedDate;

        if (Math.abs(now - folder.lastChecked) > DateUtils.WEEK_IN_MILLIS) {
            formattedDate = getString(R.string.preposition_for_date,
                    DateUtils.formatDateTime(context, folder.lastChecked, flags));
        } else {
            formattedDate = DateUtils.getRelativeTimeSpanString(folder.lastChecked,
                    now, DateUtils.MINUTE_IN_MILLIS, flags);
        }

        folderStatus = getString(folder.pushActive
                        ? R.string.last_refresh_time_format_with_push
                        : R.string.last_refresh_time_format,
                formattedDate);
    } else {
        folderStatus = null;
    }
    return folderStatus;
}
项目:TimePicker    文件:RadialPickerLayout.java   
/**
 * 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);
}
项目:chromium-for-android-56-debug-video    文件:DataReductionPreferences.java   
private static NetworkStatsHistory getNetworkStatsHistory(long[] history, int days) {
    if (days > history.length) days = history.length;
    NetworkStatsHistory networkStatsHistory =
            new NetworkStatsHistory(
                    DateUtils.DAY_IN_MILLIS, days, NetworkStatsHistory.FIELD_RX_BYTES);

    DataReductionProxySettings config = DataReductionProxySettings.getInstance();
    long time = config.getDataReductionLastUpdateTime() - days * DateUtils.DAY_IN_MILLIS;
    for (int i = history.length - days, bucket = 0; i < history.length; i++, bucket++) {
        NetworkStats.Entry entry = new NetworkStats.Entry();
        entry.rxBytes = history[i];
        long startTime = time + (DateUtils.DAY_IN_MILLIS * bucket);
        // Spread each day's record over the first hour of the day.
        networkStatsHistory.recordData(
                startTime, startTime + DateUtils.HOUR_IN_MILLIS, entry);
    }
    return networkStatsHistory;
}
项目:DateTimePicker    文件:TimePickerClockDelegate.java   
@Override
public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
    int flags = DateUtils.FORMAT_SHOW_TIME;
    if (mIs24Hour) {
        flags |= DateUtils.FORMAT_24HOUR;
    } else {
        flags |= DateUtils.FORMAT_12HOUR;
    }

    mTempCalendar.set(Calendar.HOUR_OF_DAY, getHour());
    mTempCalendar.set(Calendar.MINUTE, getMinute());

    final String selectedTime = DateUtils.formatDateTime(mContext,
            mTempCalendar.getTimeInMillis(), flags);
    final String selectionMode = mRadialTimePickerView.getCurrentItemShowing() == HOUR_INDEX ?
            mSelectHours : mSelectMinutes;
    event.getText().add(selectedTime + " " + selectionMode);
}
项目:xyz-reader-2    文件:ArticleListActivity.java   
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    mCursor.moveToPosition(position);
    holder.titleView.setText(mCursor.getString(ArticleLoader.Query.TITLE));
    holder.subtitleView.setText(
            DateUtils.getRelativeTimeSpanString(
                    mCursor.getLong(ArticleLoader.Query.PUBLISHED_DATE),
                    System.currentTimeMillis(), DateUtils.HOUR_IN_MILLIS,
                    DateUtils.FORMAT_ABBREV_ALL).toString()
                    + " by "
                    + mCursor.getString(ArticleLoader.Query.AUTHOR));
    holder.thumbnailView.setImageUrl(
            mCursor.getString(ArticleLoader.Query.THUMB_URL),
            ImageLoaderHelper.getInstance(ArticleListActivity.this).getImageLoader());
    holder.thumbnailView.setAspectRatio(mCursor.getFloat(ArticleLoader.Query.ASPECT_RATIO));
}
项目:mobile-grammar    文件:WebViewActivity.java   
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.create_reminder_menu_item) {
        Intent intent = new Intent();

        // mimeType will popup the chooser any  for any implementing application (e.g. the built in calendar or applications such as "Business calendar"
        intent.setType("vnd.android.cursor.item/event");

        // the time the event should start in millis. This example uses now as the start time and ends in 1 hour
        intent.putExtra("beginTime", new Date().getTime());
        intent.putExtra("endTime", new Date().getTime() + DateUtils.HOUR_IN_MILLIS);

        intent.putExtra("title", getString(R.string.text_reminder_about_lesson));
        intent.putExtra("description", getString(R.string.text_reminder_about_lesson) + ":" + lessonName);

        // the action
        intent.setAction(Intent.ACTION_EDIT);
        startActivity(intent);
    }

    return super.onOptionsItemSelected(item);
}
项目:Brevent    文件:AppsItemAdapter.java   
static void updateDescription(BreventActivity activity, AppsItemViewHolder viewHolder) {
    String description = activity.getDescription(viewHolder.packageName);
    if (description != null) {
        viewHolder.descriptionView.setText(description);
    } else if (activity.hasStats()) {
        UsageStats stats = activity.getStats(viewHolder.packageName);
        if (stats == null) {
            viewHolder.descriptionView.setText(R.string.process_no_stats);
        } else {
            viewHolder.descriptionView.setText(activity.getString(R.string.process_stats,
                    DateUtils.formatSameDayTime(stats.getLastTimeUsed(),
                            System.currentTimeMillis(), DateFormat.SHORT, DateFormat.SHORT),
                    DateUtils.formatElapsedTime(stats.getTotalTimeInForeground() / 1000)));
        }
    } else {
        viewHolder.descriptionView.setText(R.string.process_not_running);
    }
}
项目:AssistantBySDK    文件:RadialPickerLayout.java   
/**
 * 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);
}
项目:FireFiles    文件:Utils.java   
public static String formatTime(Context context, long when) {
    // TODO: DateUtils should make this easier
    Time then = new Time();
    then.set(when);
    Time now = new Time();
    now.setToNow();

    int flags = DateUtils.FORMAT_NO_NOON | DateUtils.FORMAT_NO_MIDNIGHT | DateUtils.FORMAT_ABBREV_ALL;

    if (then.year != now.year) {
        flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
    } else if (then.yearDay != now.yearDay) {
        flags |= DateUtils.FORMAT_SHOW_DATE;
    } else {
        flags |= DateUtils.FORMAT_SHOW_TIME;
    }

    return DateUtils.formatDateTime(context, when, flags);
}
项目:Nird2    文件:UiUtils.java   
public static String formatDate(Context ctx, long time) {
    int flags = FORMAT_ABBREV_RELATIVE |
            FORMAT_SHOW_DATE | FORMAT_ABBREV_TIME | FORMAT_ABBREV_MONTH;

    long diff = System.currentTimeMillis() - time;
    if (diff < MIN_DATE_RESOLUTION) return ctx.getString(R.string.now);
    if (diff >= DAY_IN_MILLIS && diff < WEEK_IN_MILLIS) {
        // also show time when older than a day, but newer than a week
        return DateUtils.getRelativeDateTimeString(ctx, time,
                MIN_DATE_RESOLUTION, WEEK_IN_MILLIS, flags).toString();
    }
    // otherwise just show "...ago" or date string
    return DateUtils.getRelativeTimeSpanString(time,
            System.currentTimeMillis(),
            MIN_DATE_RESOLUTION, flags).toString();
}
项目:simple-share-android    文件:Utils.java   
public static String formatTime(Context context, long when) {
    // TODO: DateUtils should make this easier
    Time then = new Time();
    then.set(when);
    Time now = new Time();
    now.setToNow();

    int flags = DateUtils.FORMAT_NO_NOON | DateUtils.FORMAT_NO_MIDNIGHT | DateUtils.FORMAT_ABBREV_ALL;

    if (then.year != now.year) {
        flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
    } else if (then.yearDay != now.yearDay) {
        flags |= DateUtils.FORMAT_SHOW_DATE;
    } else {
        flags |= DateUtils.FORMAT_SHOW_TIME;
    }

    return DateUtils.formatDateTime(context, when, flags);
}
项目:RxGooglePhotos    文件:MainActivity.java   
@Override
public void photoClicked(PhotoEntry photo) {
    ExifTags exifTags = photo.getExifTags();

    String dateTime = DateUtils.formatDateTime(MainActivity.this, photo.getGphotoTimestamp(),
            DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);
    String camera = exifTags.getExifMake() + " " + exifTags.getExifModel();

    new MaterialDialog.Builder(MainActivity.this)
            .content("Time: " + dateTime
                    + "\n" + "Camera: " + camera
                    + "\n" + "ISO: " + exifTags.getExifIso()
                    + "\n" + "F-Stop: " + exifTags.getExifFstop()
                    + "\n" + "Exposure: 1/" + (int) (1 / exifTags.getExifExposure() + 0.5) + "s"
                    + "\n" + "Focal Length: " + exifTags.getExifFocalLength() + "mm"
                    + "\n" + "Distance: " + exifTags.getExifDistance())
            .positiveText(android.R.string.ok)
            .show();
}
项目:MyBP    文件:NotificationActivity.java   
@Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, hour);
    calendar.set(Calendar.MINUTE, minute);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    editor.putLong("notificationPeriod", calendar.getTimeInMillis());
    editor.commit();

    Intent intent = new Intent(NotificationActivity.this, NotificationReceiver.class);
    intent.setAction(NotificationReceiver.ACTION_NOTIFICATION);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(NotificationActivity.this, 0, intent, 0);
    AlarmManager manager = (AlarmManager) NotificationActivity.this.getSystemService(Context.ALARM_SERVICE);
    manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 60000, pendingIntent);

    Toast.makeText(NotificationActivity.this, DateUtils.formatDateTime(NotificationActivity.this, calendar.getTimeInMillis(), DateUtils.FORMAT_SHOW_TIME), Toast.LENGTH_LONG).show();
}
项目:underlx    文件:DisturbanceRecyclerViewAdapter.java   
/**
 * Inflates the views in the layout.
 *
 * @param context the current context for the view.
 */
private void initializeViews(Context context) {
    LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.fragment_disturbance_status_view, this);

    TextView timeView = (TextView) findViewById(R.id.time_view);
    TextView statusView = (TextView) findViewById(R.id.status_view);
    ImageView iconView = (ImageView) findViewById(R.id.icon_view);

    timeView.setText(DateUtils.formatDateTime(context, status.date.getTime(), DateUtils.FORMAT_SHOW_TIME));
    statusView.setText(status.status);

    if(status.isDowntime) {
        iconView.setVisibility(GONE);
    } else {
        iconView.setVisibility(VISIBLE);
    }
}
项目:financisto1-holo    文件:TransactionInfoDialog.java   
private View createTitleView(TransactionInfo ti, LinearLayout layout) {
    View titleView = layoutInflater.inflate(R.layout.info_dialog_title, null);
    TextView titleLabel = (TextView) titleView.findViewById(R.id.label);
    TextView titleData = (TextView) titleView.findViewById(R.id.data);
    ImageView titleIcon = (ImageView) titleView.findViewById(R.id.icon);
    if (ti.isTemplate()) {
        titleLabel.setText(ti.templateName);
    } else {
        if (ti.isScheduled() && ti.recurrence != null) {
            Recurrence r = Recurrence.parse(ti.recurrence);
            titleLabel.setText(r.toInfoString(context));
        } else {
            int titleId = ti.isSplitParent()
                    ? R.string.split
                    : (ti.toAccount == null ? R.string.transaction : R.string.transfer);
            titleLabel.setText(titleId);
            add(layout, R.string.date, DateUtils.formatDateTime(context, ti.dateTime,
                    DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_YEAR),
                    ti.attachedPicture);
        }
    }
    TransactionStatus status = ti.status;
    titleData.setText(context.getString(status.titleId));
    titleIcon.setImageResource(status.iconId);
    return titleView;
}
项目:Cable-Android    文件:InputPanel.java   
@Override
public void run() {
  long localStartTime = startTime.get();
  if (localStartTime > 0) {
    long elapsedTime = System.currentTimeMillis() - localStartTime;
    recordTimeView.setText(DateUtils.formatElapsedTime(TimeUnit.MILLISECONDS.toSeconds(elapsedTime)));
    handler.postDelayed(this, TimeUnit.SECONDS.toMillis(1));
  }
}
项目:simple-share-android    文件:NonMediaDocumentsProvider.java   
private void includeFile(MatrixCursor result, Cursor cursor) {
    final long id = cursor.getLong(FileQuery._ID);
    final String docId = getDocIdForIdent(TYPE_APK, id);

    final RowBuilder row = result.newRow();
    row.add(Document.COLUMN_DOCUMENT_ID, docId);
    row.add(Document.COLUMN_DISPLAY_NAME, cursor.getString(FileQuery.TITLE));
    row.add(Document.COLUMN_SIZE, cursor.getLong(FileQuery.SIZE));
    row.add(Document.COLUMN_MIME_TYPE, cursor.getString(FileQuery.MIME_TYPE));
    row.add(Document.COLUMN_PATH, cursor.getString(FileQuery.DATA));
    row.add(Document.COLUMN_LAST_MODIFIED,
            cursor.getLong(FileQuery.DATE_MODIFIED) * DateUtils.SECOND_IN_MILLIS);
    row.add(Document.COLUMN_FLAGS, Document.FLAG_SUPPORTS_THUMBNAIL | Document.FLAG_SUPPORTS_DELETE);
}
项目:orgzly-android    文件:UserTimeFormatter.java   
public String formatTimeAndEndTime(OrgDateTime time) {
    long t1 = time.getCalendar().getTimeInMillis();
    long t2 = time.getEndCalendar().getTimeInMillis();

    int flags = DateUtils.FORMAT_SHOW_TIME;

    return format(t1, t2, flags);
}
项目:GitHub    文件:DatePickerDialog.java   
private void updateDisplay(boolean announce) {
       /*if (mDayOfWeekView != null) {
           mDayOfWeekView.setText(mCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG,
                   Locale.getDefault()).toUpperCase(Locale.getDefault()));
       }

       mSelectedMonthTextView.setText(mCalendar.getDisplayName(Calendar.MONTH, Calendar.SHORT,
               Locale.getDefault()).toUpperCase(Locale.getDefault()));*/

       if (this.mDayOfWeekView != null){
           this.mCalendar.setFirstDayOfWeek(mWeekStart);
           this.mDayOfWeekView.setText(mDateFormatSymbols.getWeekdays()[this.mCalendar.get(Calendar.DAY_OF_WEEK)].toUpperCase(Locale.getDefault()));
       }

       this.mSelectedMonthTextView.setText(mDateFormatSymbols.getMonths()[this.mCalendar.get(Calendar.MONTH)].toUpperCase(Locale.getDefault()));

       mSelectedDayTextView.setText(DAY_FORMAT.format(mCalendar.getTime()));
       mYearView.setText(YEAR_FORMAT.format(mCalendar.getTime()));

       // Accessibility.
       long millis = mCalendar.getTimeInMillis();
       mAnimator.setDateMillis(millis);
       int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR;
       String monthAndDayText = DateUtils.formatDateTime(getActivity(), millis, flags);
       mMonthAndDayView.setContentDescription(monthAndDayText);

       if (announce) {
           flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
           String fullDateText = DateUtils.formatDateTime(getActivity(), millis, flags);
           Utils.tryAccessibilityAnnounce(mAnimator, fullDateText);
       }
}
项目:GitHub    文件:SimpleMonthView.java   
private String getMonthAndYearString() {
    int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_NO_MONTH_DAY;
    mStringBuilder.setLength(0);
    long millis = mCalendar.getTimeInMillis();
    return DateUtils.formatDateRange(getContext(), millis, millis, flags);
}
项目:FireFiles    文件:MediaDocumentsProvider.java   
private void includeAudio(MatrixCursor result, Cursor cursor) {
    final long id = cursor.getLong(SongQuery._ID);
    final String docId = getDocIdForIdent(TYPE_AUDIO, id);

    final RowBuilder row = result.newRow();
    row.add(Document.COLUMN_DOCUMENT_ID, docId);
    row.add(Document.COLUMN_DISPLAY_NAME, cursor.getString(SongQuery.TITLE));
    row.add(Document.COLUMN_SIZE, cursor.getLong(SongQuery.SIZE));
    row.add(Document.COLUMN_MIME_TYPE, cursor.getString(SongQuery.MIME_TYPE));
    row.add(Document.COLUMN_PATH, cursor.getString(SongQuery.DATA));
    row.add(Document.COLUMN_LAST_MODIFIED,
            cursor.getLong(SongQuery.DATE_MODIFIED) * DateUtils.SECOND_IN_MILLIS);
    row.add(Document.COLUMN_FLAGS, Document.FLAG_SUPPORTS_THUMBNAIL | Document.FLAG_SUPPORTS_DELETE);
}
项目:iosched-reader    文件:UIUtils.java   
/**
 * Format and return the given time interval using {@link Config#CONFERENCE_TIMEZONE}
 * (unless local time was explicitly requested by the user).
 */
public static String formatIntervalTimeString(long intervalStart, long intervalEnd,
        StringBuilder recycle, Context context) {
    if (recycle == null) {
        recycle = new StringBuilder();
    } else {
        recycle.setLength(0);
    }
    Formatter formatter = new Formatter(recycle);
    return DateUtils.formatDateRange(context, formatter, intervalStart, intervalEnd, TIME_FLAGS,
            SettingsUtils.getDisplayTimeZone(context).getID()).toString();
}
项目:OpenHomeAnalysis    文件:OhaEnergyUseDayHolder.java   
@Override
public void bindView(final Cursor cursor, final IOhaMainHolder iOhaMainHolder) {
    Context context = this.itemView.getContext();
    final long beginDate = cursor.getLong(EnergyUseLogEntry.INDEX_COLUMN_CALC_DATE);
    final double kwhCost = cursor.getDouble(EnergyUseLogEntry.INDEX_COLUMN_CALC_KWH_COST);
    Double duration = cursor.getDouble(EnergyUseLogEntry.INDEX_COLUMN_CALC_DURATION_SUN);
    Double totalKWH = OhaHelper.convertWhToKWH(cursor.getDouble(EnergyUseLogEntry.INDEX_COLUMN_CALC_WH_TOTAL_SUN));
    Double dailyCost = totalKWH * kwhCost;
    Double avgKWH = totalKWH > 0 ? totalKWH / OhaHelper.convertMillisToHours(duration * 1000) : 0.00;
    Double wattsMax = cursor.getDouble(EnergyUseLogEntry.INDEX_COLUMN_CALC_WATTS_MAX);
    String titleDay = OhaHelper.formatDate(beginDate, "EEE, dd MMM yyyy");
    this.textViewDay.setText(OhaHelper.formatCamelCase(titleDay));
    this.textViewAccuracy.setText(OhaHelper.formatAccuracyDay(context, duration, DateUtils.isToday(beginDate)));
    String strCost =  OhaHelper.formatMoney(dailyCost, "#0.00");
    this.textViewDailyCost.setText(strCost);
    String body = context.getString(R.string.energy_use_day_card_body, OhaHelper.formatNumber(totalKWH, "#0.00"), OhaHelper.formatNumber(avgKWH, "#0.00"));
    this.textViewBody.setText(body);
    this.textViewWattsMax.setText(OhaHelper.formatNumber(wattsMax, ",##0.00"));
    this.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (iOhaMainHolder != null) {
                iOhaMainHolder.onEnergyUseDaySelect(beginDate, kwhCost, R.id.action_details);
            }
        }
    });

    this.toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            iOhaMainHolder.onEnergyUseDaySelect(beginDate, kwhCost, item.getItemId() );
            return true;
        }
    });
}
项目:DateTimePicker    文件:TimePickerSpinnerDelegate.java   
@Override
public void onPopulateAccessibilityEvent(AccessibilityEvent event) {
    int flags = DateUtils.FORMAT_SHOW_TIME;
    if (mIs24HourView) {
        flags |= DateUtils.FORMAT_24HOUR;
    } else {
        flags |= DateUtils.FORMAT_12HOUR;
    }
    mTempCalendar.set(Calendar.HOUR_OF_DAY, getHour());
    mTempCalendar.set(Calendar.MINUTE, getMinute());
    String selectedDateUtterance = DateUtils.formatDateTime(mContext,
            mTempCalendar.getTimeInMillis(), flags);
    event.getText().add(selectedDateUtterance);
}
项目:OpenHomeAnalysis    文件:OhaEnergyUseWhHolder.java   
public void bindView(OhaEnergyUseLogHelper.EnergyUseWh energyUseWh, final double kwhCost, final IOhaEnergyUseWhHolder iOhaEnergyUseWhHolder) {
    double totalKwh = OhaHelper.convertWhToKWH(energyUseWh.whTotal);
    String hour = OhaHelper.formatDate(energyUseWh.dateTime, "HH");
    this.textViewHour.setText(hour);
    this.textViewDuration.setText(DateUtils.formatElapsedTime((long) energyUseWh.duration));
    if (this.textViewWh1 != null) {
        this.textViewWh1.setText(OhaHelper.formatNumber(energyUseWh.wh1, "#,##0.00"));
        this.textViewWh2.setText(OhaHelper.formatNumber(energyUseWh.wh2, "#,##0.00"));
        this.textViewWh3.setText(OhaHelper.formatNumber(energyUseWh.wh3, "#,##0.00"));
    }
    this.textViewKwh.setText(OhaHelper.formatNumber(totalKwh, "#,##0.00"));
    this.textViewCost.setText(OhaHelper.formatNumber(totalKwh * kwhCost, "#,##0.00"));


    Date date = new Date(energyUseWh.dateTime);
    final long beginDateHour = OhaHelper.getBeginHour(date).getTime();
    final long endDateHour = OhaHelper.getEndHour(date, false).getTime();

    radioButtonHour.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            iOhaEnergyUseWhHolder.onSelectedEnergyUseWh(beginDateHour, endDateHour, kwhCost);
            radioButtonHour.setChecked(false);
        }
    });


}
项目:tumbviewer    文件:PhotoPostVH.java   
private String formatTime(String duration) {
    try {
        long dur = Long.valueOf(duration);
        return DateUtils.formatElapsedTime(dur);
    } catch (NumberFormatException e) {
        return duration;
    }
}
项目:OpenHomeAnalysis    文件:OhaEnergyUseLogTask.java   
/**
 * Atualizar o status e data hora do Registrador de Utilização de Energia
 * com a data e hora atual.
 * @throws IOException se o Registrador não for localizado na Rede.
 */
private void setStatus() throws IOException {
    Date date = new Date();
    String strDate = OhaHelper.getStrDate(date);
    String strTime = OhaHelper.getStrTime(date);
    OhaEnergyUseApi.setStatus(ohaEnergyUseSyncHelper.getHostName(), strDate, strTime);
    //O Registrador não é multitarefas, dessa forma, e necessário executar delays
    //no fluxo de sincronização para não parar os registros de utilização de energia/
    // por muito tempo:
    delay(DateUtils.SECOND_IN_MILLIS * 5);
}
项目:NumberPadTimePicker    文件:DateTimeFormatUtils.java   
/**
 * @return The time separator used in the user's locale.
 */
static String getTimeSeparator(@NonNull Context context, boolean is24Hour) {
    // The time separator is defined in the Unicode CLDR and cannot be supposed to be ":".
    // See http://unicode.org/cldr/trac/browser/trunk/common/main.
    if (Build.VERSION.SDK_INT >= 18) {
        // We pass the correct "skeleton" depending on 12 or 24 hours view and then extract the
        // separator, which is the character just after the hour marker in the returned pattern.
        final String bestDateTimePattern = DateFormat.getBestDateTimePattern(
                getPrimaryLocale(context), (is24Hour) ? "Hm" : "hm");
        final String separatorText;
        // See http://www.unicode.org/reports/tr35/tr35-dates.html for hour formats
        final char[] hourFormats = {'H', 'h', 'K', 'k'};
        int hIndex = lastIndexOfAny(bestDateTimePattern, hourFormats);
        if (hIndex == -1) {
            // Default case
            separatorText = ":";
        } else {
            separatorText = Character.toString(bestDateTimePattern.charAt(hIndex + 1));
        }
        return separatorText;
    } else {
        // Format a dummy time string in 24-hour time, then iterate through the string until
        // we find a non-digit character.
        final String formatted24HourTime = DateUtils.formatDateTime(context,
                System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_24HOUR);
        for (int i = 0; i < formatted24HourTime.length(); i++) {
            final char c = formatted24HourTime.charAt(i);
            if (!Character.isDigit(c)) {
                return Character.toString(c);
            }
        }
        return "";
    }
}
项目:orgzly-android    文件:BooksFragment.java   
private String timeString(long ts) {
    int flags = DateUtils.FORMAT_SHOW_DATE |
            DateUtils.FORMAT_SHOW_TIME |
            DateUtils.FORMAT_ABBREV_MONTH |
            DateUtils.FORMAT_SHOW_WEEKDAY |
            DateUtils.FORMAT_ABBREV_WEEKDAY;

    return DateUtils.formatDateTime(getContext(), ts, flags);
}
项目:GroupingMessages    文件:SmsListItemHolder.java   
private String getDate(long milliSeconds) {

        return DateUtils.getRelativeDateTimeString(
                context,
                milliSeconds,
                DateUtils.MINUTE_IN_MILLIS,
                DateUtils.WEEK_IN_MILLIS,
                DateUtils.FORMAT_ABBREV_TIME
        ).toString();
    }
项目:Melophile    文件:TrackFragment.java   
private void updateDuration(MediaMetadataCompat metadataCompat){
    if(metadataCompat==null) return;
    int duration=(int)metadataCompat.getLong(MediaMetadataCompat.METADATA_KEY_DISC_NUMBER);
    startTime.setText(DateUtils.formatElapsedTime(duration/1000));
    duration=(int)metadataCompat.getLong(MediaMetadataCompat.METADATA_KEY_DURATION);
    endTime.setText(DateUtils.formatElapsedTime(duration/1000));
    progress.setMax(duration);
}
项目:mvvm-template    文件:ParseDateFormat.java   
@NonNull public static CharSequence getTimeAgo(@Nullable Date parsedDate) {
    if (parsedDate != null) {
        long now = System.currentTimeMillis();
        return DateUtils.getRelativeTimeSpanString(parsedDate.getTime(), now, DateUtils.SECOND_IN_MILLIS);
    }
    return "N/A";
}
项目:simple-share-android    文件:MediaDocumentsProvider.java   
private void includeVideosBucket(MatrixCursor result, Cursor cursor) {
    final long id = cursor.getLong(VideosBucketQuery.BUCKET_ID);
    final String docId = getDocIdForIdent(TYPE_VIDEOS_BUCKET, id);

    final RowBuilder row = result.newRow();
    row.add(Document.COLUMN_DOCUMENT_ID, docId);
    row.add(Document.COLUMN_DISPLAY_NAME,
            cursor.getString(VideosBucketQuery.BUCKET_DISPLAY_NAME));
    row.add(Document.COLUMN_MIME_TYPE, Document.MIME_TYPE_DIR);
    row.add(Document.COLUMN_LAST_MODIFIED,
            cursor.getLong(VideosBucketQuery.DATE_MODIFIED) * DateUtils.SECOND_IN_MILLIS);
    row.add(Document.COLUMN_FLAGS, Document.FLAG_DIR_PREFERS_GRID
            | Document.FLAG_SUPPORTS_THUMBNAIL | Document.FLAG_DIR_PREFERS_LAST_MODIFIED
            | Document.FLAG_DIR_HIDE_GRID_TITLES | Document.FLAG_SUPPORTS_DELETE);
}
项目:permitlog-android    文件:ElapsedTime.java   
public static String formatSeconds(long seconds) {
    /* Takes number of seconds and returns a String with format HH:MM. */
    String timeString = DateUtils.formatElapsedTime(seconds);
    //If the time is less than an hour, then add "00:" to the beginning:
    if (seconds < 3600) timeString = "00:" + timeString;
    //Otherwise, if the time is less than 10 hours, then add "0" to the beginning:
    else if (seconds < 36000) timeString = "0" + timeString;
    //Removes seconds from time, because it's unneeded information
    return timeString.substring(0, timeString.length()-3);
}
项目:permitlog-android    文件:LogFragment.java   
private String genLogSummary(DataSnapshot dataSnapshot) {
    //Find the time elapsed during the drive:
    long driveTimeInSec =
            ((long)(dataSnapshot.child("end").getValue())-(long)(dataSnapshot.child("start").getValue()))/1000;

    //Format the time appropriately:
    String driveTimeString = ElapsedTime.formatSeconds(driveTimeInSec);
    //Format the date based off the starting time:
    String driveDate = DateUtils.formatDateTime(getContext(),
            (long)(dataSnapshot.child("start").getValue()), FORMAT_NUMERIC_DATE | FORMAT_SHOW_YEAR);

    //Finally return the time with the date:
    return (driveTimeString + " on " + driveDate);
}
项目:downloadmanager    文件:DownloadProvider.java   
@Override
public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {

    Log.d("dump", "Downloads updated in last hour:");

    final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
    final long modifiedAfter = System.currentTimeMillis() - DateUtils.HOUR_IN_MILLIS;
    final Cursor cursor = db.query(DB_TABLE, null,
            Downloads.Impl.COLUMN_LAST_MODIFICATION + ">" + modifiedAfter, null, null, null,
            Downloads.Impl._ID + " ASC");
    try {
        final String[] cols = cursor.getColumnNames();
        final int idCol = cursor.getColumnIndex(BaseColumns._ID);
        while (cursor.moveToNext()) {
            Log.d("dump", "Download #" + cursor.getInt(idCol) + ":");
            for (int i = 0; i < cols.length; i++) {
                // Omit sensitive data when dumping
                if (Downloads.Impl.COLUMN_COOKIE_DATA.equals(cols[i])) {
                    continue;
                }
                Log.d("dump", cols[i] + ", " + cursor.getString(i));
            }
        }
    } finally {
        cursor.close();
    }

}
项目:XinFramework    文件:FileUtil.java   
public static int clearCacheFolder(final File dir,
                                   final int numDays) {

    int deletedFiles = 0;
    if (dir != null && dir.isDirectory()) {
        try {
            for (File child : dir.listFiles()) {

                // first delete subdirectories recursively
                if (child.isDirectory()) {
                    deletedFiles += clearCacheFolder(child,
                            numDays);
                }

                // then delete the files and subdirectories in this dir
                // only empty directories can be deleted, so subDirs have
                // been done first
                if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
                    if (child.delete()) {
                        deletedFiles++;
                    }
                }
            }
        } catch (Exception e) {
            Log.e(e, "clearCacheFolder");
        }
    }
    return deletedFiles;
}