Advertisement

Android之判断时间戳是不是今天

阅读量:

该系统实现了判断给定时间戳是否为今天的功能,包含获取当天零点时间戳的方法和日期比较逻辑。

1 需求

判断时间戳是不是今天

2、工具代码

复制代码
  
    
     /** * 获取每日0点时间
    
      * @return
    
      */
    
     fun getTodayTime(timeStamp: Long): Long {
    
         val cal = Calendar.getInstance()
    
         cal.timeInMillis = timeStamp
    
         cal.set(Calendar.HOUR_OF_DAY, 0)
    
         cal.set(Calendar.SECOND, 0)
    
         cal.set(Calendar.MINUTE, 0)
    
         cal.set(Calendar.MILLISECOND, 0)
    
         return cal.timeInMillis
    
     }
    
 		
    
  
    
     fun isToday(time: Long): Boolean {
    
         val sdf = SimpleDateFormat("yyyy-MM-dd")
    
         val date = Date(time)
    
         return try {
    
             val old = sdf.parse(sdf.format(date))
    
             val now = sdf.parse(sdf.format(Date()))
    
             val oldTime = old.time
    
             val nowTime = now.time
    
             val day = (nowTime - oldTime) / (24 * 60 * 60 * 1000)
    
             Log.d(TAG, "handleDate: day is ${day}")
    
             if (day < 0) {
    
                 return false
    
             }
    
             if (day < 1) {  //今天
    
                 //                SimpleDateFormat format = new SimpleDateFormat("HH:mm");
    
                 //                return format.format(date);
    
                 Log.i(TAG, "is today")
    
                 return true
    
             } else if (day == 1L) {     //昨天
    
                 //                SimpleDateFormat format = new SimpleDateFormat("HH:mm");
    
                 //                return "昨天 " + format.format(date);
    
                 Log.i(TAG, "is yesterday")
    
                 return false
    
             } else {    //可依次类推
    
                 //                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
    
                 //                return format.format(date);
    
                 Log.i(TAG, "no today no yesterday")
    
                 return false
    
             }
    
         } catch (e: Exception) {
    
             Log.i(TAG, "handleDate has error")
    
             e.printStackTrace()
    
             return false
    
         }
    
     }
    
 		
    
 		
    
 		var dayTime = getTodayTime(time)
    
 		var dayTime = TimeUtils.getTodayTime(time)
    
     Log.d(TAG, "getTodayAdbSize: dayTime is ${dayTime}")

全部评论 (0)

还没有任何评论哟~