java开发过程中常用方法

1.阿里fastjson使用
//用户组对象转JSON串
String jsonString = JSON.toJSONString(group);
//JSON串转用户组对象
UserGroup group2 = JSON.parseObject(jsonString, UserGroup.class);

// 用户对象数组转JSON串
String jsonString2 = JSON.toJSONString(users);
// JSON串转用户对象列表
List users2 = JSON.parseArray(jsonString2, User.class);

2.日期转化
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
//日期格式转字符串
sdf.format();
//字符串转日期格式
sdf.parse();

3.日期计算
计算两个日期相差天数

/**
 * 计算日期相差天数
 * @return int
 */
public static int getDaysBetween(Calendar cal01,Calendar cal02){
    if(cal01.after(cal02)){
        Calendar swap = cal01;
        cal01 = cal02;
        cal02 = swap;
    }
    int days = cal02.get(Calendar.DAY_OF_YEAR) - cal01.get(Calendar.DAY_OF_YEAR);
    int year2 = cal02.get(Calendar.YEAR);
    if(cal01.get(Calendar.YEAR) != year2){
        cal01 = (Calendar) cal01.clone();
        do {
            //得到当年实际天数
            days += cal01.getActualMaximum(Calendar.DAY_OF_YEAR);
            cal01.add(Calendar.YEAR,1);
        }while (cal01.get(Calendar.YEAR) != year2);
    }
    return days;
}

计算一天剩余天数

/**
 * 获取截至当天的时间差 单位秒
 * @return
 */
public static int getStartTimeOfDay(String timeZone){
    //时区
    String tz = StringUtils.isEmpty(timeZone)?"GMT+8":timeZone;
    TimeZone curTz = TimeZone.getTimeZone(tz);
    Calendar calendar = Calendar.getInstance(curTz);
    Date date = new Date();
    calendar.setTime(date);
    calendar.add(Calendar.DAY_OF_MONTH,1);
    calendar.set(Calendar.HOUR_OF_DAY,0);
    calendar.set(Calendar.MINUTE,0);
    calendar.set(Calendar.SECOND,0);
    calendar.set(Calendar.MILLISECOND,0);
    return (int) ((calendar.getTime().getTime() - date.getTime())/1000);
}

/**
 * 基于jdk8 获取当天剩余时间 单位秒
 * @param currentDate
 * @return
 */
public static int getEndTimeOfDay(Date currentDate){
    LocalDateTime night = LocalDateTime.ofInstant(currentDate.toInstant(),
            ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
    LocalDateTime curr = LocalDateTime.ofInstant(currentDate.toInstant(),ZoneId.systemDefault());
    return (int) ChronoUnit.SECONDS.between(curr,night);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值