DateUtils.java 7.07 KB
/*
 * Copyright 2014 Qunar.com All right reserved. This software is the
 * confidential and proprietary information of Qunar.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with Qunar.com.
 */
package com.canrd.patent.common.utils;

import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.LocalTime;
import org.joda.time.Period;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 实现描述:日期处理工具
 *
 * @author chaoyi.he
 * @version v1.0.0
 * @see 
 * @since 2014年8月13日 上午10:48:36
 */
public abstract class DateUtils {

    public static String now() {
        return format(new Date());
    }

    public static String format(Date time) {
        return format(time, "yyyy-MM-dd HH:mm:ss");
    }

    public static String formatDate(Date date) {
        return format(date, "yyyy-MM-dd");
    }

    public static String format(Date time, String pattern) {
        return new DateTime(time).toString(pattern);
    }

    public static Date parse(String time) {
        return DateTime.parse(time.replace(' ', 'T')).toDate();
    }

    public static Date parseTime(String time) {
        if (time.startsWith("24:00"))
            return new DateTime().plusDays(1).withTimeAtStartOfDay().minusMillis(1).toDate();
        return LocalTime.parse(time).toDateTimeToday().toDate();
    }

    public static String formatToHMS(Date start, Date finish) {
        Period period = new Period(start.getTime(), finish.getTime());
        return String.format("%02d:%02d:%02d.%03d", period.toStandardHours().getHours(), period.getMinutes(),
                period.getSeconds(), period.getMillis());
    }

    public static String formatToHMS(int millis) {
        Period period = new Period(millis);
        return String.format("%02d:%02d:%02d.%03d", period.toStandardHours().getHours(), period.getMinutes(),
                period.getSeconds(), period.getMillis());
    }

    public static String formatToMS(Date start, Date finish) {
        Period period = new Period(start.getTime(), finish.getTime());
        return String.format("%02d:%02d.%03d", period.toStandardMinutes().getMinutes(), period.getSeconds(),
                period.getMillis());
    }

    public static String formatToMS(int millis) {
        Period period = new Period(millis);
        return String.format("%02d:%02d.%03d", period.toStandardMinutes().getMinutes(), period.getSeconds(),
                period.getMillis());
    }

    public static int dateRange(Date startDate, Date endDate) {
        Period period = new Period(new DateTime(startDate).withTimeAtStartOfDay(),
                new DateTime(endDate).withTimeAtStartOfDay());
        return period.toStandardDays().getDays() + 1;
    }

    public static int minutesAgo(Date time) {
        Period period = new Period(new DateTime(time), new DateTime());
        return period.toStandardMinutes().getMinutes();
    }

    /**
     * 将日期或者时间字符串转化为日期对象
     *
     * @param date 日期字符串
     * @param pattern 格式字符串</br> yyyy-MM-DD, yyyy/MM/DD, yyyyMMdd</br> yyyy-MM-dd-HH:mm:ss, yyyy-MM-dd HH:mm:ss
     *            格式字符串可选字符:"GyMdkHmsSEDFwWahKzZ"
     * @return Date
     * @see java.text.DateFormatSymbols
     */
    public static Date convertDate(String date, String pattern) {
        try {
            if (StringUtils.isEmpty(pattern) || StringUtils.isEmpty(date)) {
                String msg = "the date or pattern is empty.";
                throw new IllegalArgumentException(msg);
            }
            SimpleDateFormat df = new SimpleDateFormat(pattern.trim());
            return df.parse(date.trim());
        } catch (Exception e) {
            throw new IllegalArgumentException("Method===DateUtils.convertDate error!", e);
        }
    }

    public static int diffDate(Date date1, Date date2) {
        return (int) ((date1.getTime() - date2.getTime()) / TimeUnit.DAYS.toMillis(1L));
    }

    public static Date beforeDay(Integer c) {
        Calendar calendar = Calendar.getInstance();// 此时打印它获取的是系统当前时间
        calendar.add(Calendar.DATE, -c); // 得到前一天
        String yestedayDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
        return convertDate(yestedayDate, "yyyy-MM-dd");
    }

    public static Date beforeTime(Integer c) {
        Calendar calendar = Calendar.getInstance();// 此时打印它获取的是系统当前时间
        calendar.add(Calendar.DATE, -c); // 得到前一天
        String yestedayDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
        return convertDate(yestedayDate, "yyyy-MM-dd HH:mm:ss");
    }

    public static String todayDate() {
        return format(today(), "yyyy-MM-dd");
    }

    public static String nextDays(Integer c) {
        return format(nextDay(c), "yyyy-MM-dd");
    }

    public static Date today() {
        return new Date();
    }

    public static Date nextDay(Integer c) {
        Calendar calendar = Calendar.getInstance();// 此时打印它获取的是系统当前时间
        calendar.add(Calendar.DATE, c); // 得到前一天
        String yestedayDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
        return convertDate(yestedayDate, "yyyy-MM-dd");
    }

    public static Date nextDayByOneDay(Date date, Integer c) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int day = calendar.get(Calendar.DATE);
        calendar.set(Calendar.DATE, day + c);
        return calendar.getTime();
    }

    public static String nextDay(Date date, int c) {
        return format(nextDayByOneDay(date, c), "yyyy-MM-dd");
    }

    /**
     * 获得指定日期的前一天
     * @param specifiedDay
     * @return
     * @throws Exception
     */
    public static String dayBefore(String specifiedDay) {
        return DateTime.parse("yyyy-MM-dd").minusDays(1).toString("yyyy-MM-dd");
    }

    public static String dayBefore(Date d) {
        return dayBefore(new SimpleDateFormat("yyyy-MM-dd").format(d));
    }

    /**
      * 返回日期是星期几(整形数字),按照国内的记法
      * 例如:星期一是1,星期二是2
      * @return
     */
    public static int dayOfWeek(Date d) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w == 0) {
            w = 7;
        }
        return w;
    }

    /**
     * 返回日期是星期几(中文),按照国内的记法
     * 
     * @return
    */
    public static String weekOfDate(Date dt) {
        String[] weekDays = { "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日" };
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w == 0) {
            w = 7;
        }
        return weekDays[w - 1];
    }

}