java时间相关

来源:互联网 发布:淘宝模特有什么要求 编辑:程序博客网 时间:2024/06/06 09:34

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

      判断当前输入的时间必须是大于当天的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
    }

原创粉丝点击