网站建设实施计划包括,网站模板修改教程,wordpress怎么集成码支付,深圳网站开发设计本文主要是Java中和日期时间相隔的几个常用代码函数代码#xff0c;做了总结#xff0c;希望在日常编码中#xff0c;可以帮到大家。
1.计算闰年
记住一个短语#xff0c;“四年一润#xff0c;百年不闰#xff0c;四百再润”#xff0c;不管换啥语言#xff0c;相信…本文主要是Java中和日期时间相隔的几个常用代码函数代码做了总结希望在日常编码中可以帮到大家。
1.计算闰年
记住一个短语“四年一润百年不闰四百再润”不管换啥语言相信大家不会写错这块的实现代码。 怎么理解呢转换为我们程序语言就是“
是4的倍数并且不是100的倍数那么是普通闰年是400的倍数那么是世纪闰年
/*** 是否是闰年* param y* return*/public static boolean isLeapYear(int y) {if (y % 4 0 y % 100 ! 0 || y % 200 0) {return true;} else {return false;}}2.SimpleDateFormat线程不安全问题
SimpleDateFormat是Java 时间处理上经常使用到的一个函数经常用于C-S直接时间戳处理为当前的格式化的时间。但是大家需要知道SimpleDateFormat、Date等函数仅仅是系统的一个功能函数而已并没有线程同步的功能所以不可以在多线程环境下共用一个SimpleDateFormat不然就会出现相同的时间戳解析出来的时间不一样的问题。 我们可以看一下SimpleDateFormat的format源码的确是没有加同步相关的处理逻辑的。 public abstract StringBuffer format(Date date, StringBuffer toAppendTo,FieldPosition fieldPosition);/*** Formats a Date into a date/time string.* param date the time value to be formatted into a time string.* return the formatted time string.*/public final String format(Date date){return format(date, new StringBuffer(),DontCareFieldPosition.INSTANCE).toString();}3.定时器的调用
3.1 CountDownTimer
Java中经常会使用到定时器经常使用的无疑是CountDownTimer CountDownTimer countDownTimer new CountDownTimer(6000, 1000) {Overridepublic void onTick(long millisUntilFinished) {//每隔1s回调}Overridepublic void onFinish() {//6s倒计时完成回调}};当然了如果在android中的可选择的API框架更多了例如Handler、Rxjava等等 Handler延迟执行 new Handler().postDelayed(new Runnable() {Overridepublic void run() {// 6s后执行的代码}}, 6000);但是这里需要注意大家如果在android中使用CountDownTimer实现倒计时相关需求时会存在跳秒的问题。 究其原因是因为handler postDealy会有消息处理第一次的跳变问题如果使用handler.postDealyed(……, 1000)方式来进行每秒的计时是不准确的是的有很大误差误差的原因在于在你收到消息到你重新发出handler.postDealyed的时间并不是瞬间完成的这里面有很多逻辑处理的时间即使没有逻辑处理的时间handler本身也是耗损性能的所以消息并不可能按照理想的1000延迟来进行发送这就导致了误差的累积怎么解决
一方面可以通过自己封装CountDownTimer来规避这个错误一方面可以借助其他第三方框架来实现例如Rxjava
package com.itbird.design.builder.dialog;import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;/*** 使用android.os.CountDownTimer的源码* 添加了onPause、onRestart自定义方法* Created by xfkang on 16/3/18.*/public abstract class CustomCountDownTimer {private static final int MSG 1;/*** 总倒计时时间* Millis since epoch when alarm should stop.*/private final long mMillisInFuture;/*** 倒计时间隔时间* The interval in millis that the user receives callbacks*/private final long mCountdownInterval;/*** 记录开始之后应该停止的时间节点*/private long mStopTimeInFuture;/*** 记录暂停的时间节点*/private long mPauseTimeInFuture;/*** 对应于源码中的cancle即计时停止时* boolean representing if the timer was cancelled*/private boolean isStop false;private boolean isPause false;/*** param millisInFuture 总倒计时时间* param countDownInterval 倒计时间隔时间*/public CustomCountDownTimer(long millisInFuture, long countDownInterval) {// 解决秒数有时会一开始就减去了2秒问题如10秒总数的刚开始就8999然后没有不会显示9秒直接到8秒if (countDownInterval 1000) {millisInFuture 15;}mMillisInFuture millisInFuture;mCountdownInterval countDownInterval;}private synchronized CustomCountDownTimer start(long millisInFuture) {isStop false;if (millisInFuture 0) {onFinish();return this;}mStopTimeInFuture SystemClock.elapsedRealtime() millisInFuture;mHandler.sendMessage(mHandler.obtainMessage(MSG));return this;}/*** 开始倒计时*/public synchronized final void start() {start(mMillisInFuture);}/*** 停止倒计时*/public synchronized final void stop() {isStop true;mHandler.removeMessages(MSG);}/*** 暂时倒计时* 调用{link #restart()}方法重新开始*/public synchronized final void pause() {if (isStop) return;isPause true;mPauseTimeInFuture mStopTimeInFuture - SystemClock.elapsedRealtime();mHandler.removeMessages(MSG);}/*** 重新开始*/public synchronized final void restart() {if (isStop || !isPause) return;isPause false;start(mPauseTimeInFuture);}/*** 倒计时间隔回调** param millisUntilFinished 剩余毫秒数*/public abstract void onTick(long millisUntilFinished);/*** 倒计时结束回调*/public abstract void onFinish();private Handler mHandler new Handler() {Overridepublic void handleMessage(Message msg) {synchronized (CustomCountDownTimer.this) {if (isStop || isPause) {return;}final long millisLeft mStopTimeInFuture - SystemClock.elapsedRealtime();if (millisLeft 0) {onFinish();} else if (millisLeft mCountdownInterval) {// no tick, just delay until donesendMessageDelayed(obtainMessage(MSG), millisLeft);} else {long lastTickStart SystemClock.elapsedRealtime();onTick(millisLeft);// take into account users onTick taking time to executelong delay lastTickStart mCountdownInterval - SystemClock.elapsedRealtime();// special case: users onTick took more than interval to// complete, skip to next intervalwhile (delay 0) delay mCountdownInterval;sendMessageDelayed(obtainMessage(MSG), delay);}}}};
}
3.2 Rxjava.interval
Rxjava.interval //每隔10s触发一下accept
Observable.interval(10, TimeUnit.SECONDS).subscribe(new ConsumerLong() {Overridepublic void accept(Long aLong) throws Exception {Log.d(TAG interval, String.valueOf(aLong));//从0开始输出}});这个相当于定时器用它可以取代CountDownTimer。它会按照设定的间隔时间每次发送一个事件发送的事件序列默认从0开始无限递增的整数序列 。 那么Rxjava.interval的实现原理是什么呢这块源码其实我们之前RxJava系列文章讲解过这里不再赘述有兴趣的小伙伴可以移步查阅。 简言之就是使用了线程池的ScheduledExecutorService 定时周期执行任务。