当前位置: 首页>>代码示例>>Java>>正文


Java DateUtils类代码示例

本文整理汇总了Java中android.text.format.DateUtils的典型用法代码示例。如果您正苦于以下问题:Java DateUtils类的具体用法?Java DateUtils怎么用?Java DateUtils使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


DateUtils类属于android.text.format包,在下文中一共展示了DateUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getLogs

import android.text.format.DateUtils; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:brolam,项目名称:OpenHomeAnalysis,代码行数:47,代码来源:OhaEnergyUseLogTask.java

示例2: setNextOhaSequenceLog

import android.text.format.DateUtils; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:brolam,项目名称:OpenHomeAnalysis,代码行数:21,代码来源:OhaEnergyUseLogTask.java

示例3: dispatchPopulateAccessibilityEvent

import android.text.format.DateUtils; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:hsj-xiaokang,项目名称:OSchina_resources_android,代码行数:20,代码来源:AccessibleDateAnimator.java

示例4: buildFolderStatus

import android.text.format.DateUtils; //导入依赖的package包/类
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;
}
 
开发者ID:philipwhiuk,项目名称:q-mail,代码行数:29,代码来源:FolderList.java

示例5: dispatchPopulateAccessibilityEvent

import android.text.format.DateUtils; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:ttpho,项目名称:TimePicker,代码行数:23,代码来源:RadialPickerLayout.java

示例6: getNetworkStatsHistory

import android.text.format.DateUtils; //导入依赖的package包/类
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;
}
 
开发者ID:rkshuai,项目名称:chromium-for-android-56-debug-video,代码行数:19,代码来源:DataReductionPreferences.java

示例7: onPopulateAccessibilityEvent

import android.text.format.DateUtils; //导入依赖的package包/类
@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);
}
 
开发者ID:Gericop,项目名称:DateTimePicker,代码行数:19,代码来源:TimePickerClockDelegate.java

示例8: onBindViewHolder

import android.text.format.DateUtils; //导入依赖的package包/类
@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));
}
 
开发者ID:rashikaranpuria,项目名称:xyz-reader-2,代码行数:17,代码来源:ArticleListActivity.java

示例9: onOptionsItemSelected

import android.text.format.DateUtils; //导入依赖的package包/类
@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);
}
 
开发者ID:white-collar,项目名称:mobile-grammar,代码行数:27,代码来源:WebViewActivity.java

示例10: updateDescription

import android.text.format.DateUtils; //导入依赖的package包/类
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);
    }
}
 
开发者ID:brevent,项目名称:Brevent,代码行数:19,代码来源:AppsItemAdapter.java

示例11: dispatchPopulateAccessibilityEvent

import android.text.format.DateUtils; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:LingjuAI,项目名称:AssistantBySDK,代码行数:24,代码来源:RadialPickerLayout.java

示例12: formatTime

import android.text.format.DateUtils; //导入依赖的package包/类
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);
}
 
开发者ID:gigabytedevelopers,项目名称:FireFiles,代码行数:20,代码来源:Utils.java

示例13: formatDate

import android.text.format.DateUtils; //导入依赖的package包/类
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();
}
 
开发者ID:rafjordao,项目名称:Nird2,代码行数:17,代码来源:UiUtils.java

示例14: photoClicked

import android.text.format.DateUtils; //导入依赖的package包/类
@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();
}
 
开发者ID:yosriz,项目名称:RxGooglePhotos,代码行数:20,代码来源:MainActivity.java

示例15: naturalDateFrom

import android.text.format.DateUtils; //导入依赖的package包/类
private CharSequence naturalDateFrom(@NonNull Date taskDueDate)
{
    return DateUtils.getRelativeDateTimeString(
            context,
            taskDueDate.getTime(),
            DateUtils.DAY_IN_MILLIS,
            DateUtils.WEEK_IN_MILLIS, 0);
}
 
开发者ID:WangZhiYao,项目名称:RealmTasks,代码行数:9,代码来源:TaskAdapter.java


注:本文中的android.text.format.DateUtils类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。