java时间相关

对时间字符串进行比较和处理

      判断当前输入的时间必须是大于当天的23:59:59的:

           String dateTime = "2017-12-13 15:50:23"//界面输入时间
        SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59")
        Calendar calendar = Calendar.getInstance()
        String mystrdate = myFormat.format(calendar.getTime()) //当天时间精确到23:59:59

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        Date beginDate = sdf.parse(dateTime)
        Date endDate = sdf.parse(mystrdate)
        if(endDate.time-beginDate.time>=0){
            print("11111")
        }else{
            print("22222")
        }

      获取当前系统时间:

        SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        Calendar calendar = Calendar.getInstance()
        String mystrdate = myFormat.format(calendar.getTime())
        print(mystrdate)

   判断时间为多久之前进行相关页面的返回:

  static String simpleRangeTimes(Long time) {
        Long cTime = getTime().time - time
        if (cTime > 0 && cTime < 600000l) return "刚刚" //0分钟<X<10分钟
        if (cTime > 600000l && cTime < 3600000l) return "1小时前"//10分钟≤X<60分钟,显示“1小时前”
        if (cTime > 3600000l && cTime < 7200000l) return "2小时前"//60分钟≤X<120分钟,显示“2小时前”
        else return formatDate(time, "yyyy-MM-dd")
    }

或者另外一种方式

   /**
     * 和当前时间比较,简洁显示
     * 1小时之前,显示到分钟;24小时之前显示到小时;1个月前显示到天
     * @param time
     * @return
     */
    static String simpleRangeTime(Long time) {
        Long cTime = getTime().time - time
        if (cTime < 60000l) return "刚刚"
        if (cTime < 3600000l) return (cTime / (1000 * 60) as int) + "分钟前"
        if (cTime < 86400000l) return (cTime / (1000 * 60 * 60) as int) + "小时前"
        if (cTime < 2592000000l) return (cTime / (1000 * 60 * 60 * 24) as int) + "天前"
        else return "很久以前"
    }

使用时间计算年龄:

/**
     * 计算年龄
     * @param birthday
     * @return
     */
    static int getAge(long birthday) {
        Calendar born = Calendar.getInstance();
        Calendar now = Calendar.getInstance();
        born.setTimeInMillis(birthday)
        now.setTimeInMillis(new Date().getTime())
        def age = now.get(Calendar.YEAR) - born.get(Calendar.YEAR)
        if (now.get(Calendar.DAY_OF_YEAR) < born.get(Calendar.DAY_OF_YEAR)) {
            age -= 1;
        }
        return age
    }
    /**
     * 计算年龄
     * @param birthday , 格式yyyy-MM-dd
     * @return
     */
    static int getAge(String birthday) {
        if (birthday) {
            return getAge(formatDate(birthday))
        }
        return 0
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值