java日期操作

ps:在android开发中有时会需要对日历控件进行优化,常用的生日选择器,签到列表……
1、日历工具类


package net.app.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;


public class DateUtil {

    private static SimpleDateFormat mDateFormat;
    private static Date mDate;
    private static Calendar calendar;
    public static final long SECONDS_OF_MINUTE = 60;
    public static final long SECONDS_OF_HOUR = 60 * 60;
    public static final long SECONDS_OF_DAY = 60 * 60 * 24;
    public static final long DAYS_OF_MONTH = 30;
    public static final long DAYS_OF_YEAR = 365;
    public static final long MINUTES_OF_HOUR = 60;
    public static final long MONTHES_OF_YEAR = 12;

    /**
     * 获取此时时间
     * 
     * @param format
     *            返回的时间格式
     * @return
     */
    public static String getNow(String format) {
        mDate = new Date();
        mDateFormat = new SimpleDateFormat(format);
        return mDateFormat.format(mDate);
    }

    /**
     * 格式化时间
     * 
     * @param date
     *            时间字符串
     * @param dFomat
     *            时间格式
     * @param fomat
     *            返回的时间格式
     * @return
     * @throws ParseException
     */
    public static String format(String date, String dateFormat, String format)
            throws ParseException {
        mDate = getDate(date, dateFormat);
        mDateFormat = new SimpleDateFormat(format);
        return mDateFormat.format(mDate);
    }

    public static String format(Date date, String format){
        mDateFormat = new SimpleDateFormat(format);
        return mDateFormat.format(date);
    }

    /**
     * 获取到date的时间秒
     * 
     * @param date
     * @param dateFormat
     * @return
     * @throws ParseException
     */
    public static long getTime(String date, String dateFormat)
            throws ParseException {
        return getDate(date, dateFormat).getTime();
    }


    /**
     * 获取到现在的时间秒
     * 
     * @return
     */
    public static long getTime() {
        mDate = new Date();
        return mDate.getTime();
    }

    public static int getYear() {
        return Calendar.getInstance().get(Calendar.YEAR);
    }

    public static int getMonth() {
        return Calendar.getInstance().get(Calendar.MONTH);
    }

    public static int getDayOfMonth() {
        return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    }

    public static int getDayOfYear() {
        return Calendar.getInstance().get(Calendar.DAY_OF_YEAR);
    }

    public static int getHourOfDay() {
        return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    }

    public static int getMinute() {
        return Calendar.getInstance().get(Calendar.MINUTE);
    }

    /**
     * 获取时间与现在的时间差
     * 
     * @param date
     * @param format
     * @return
     * @throws ParseException
     */
    public static String getHowLong(String date, String format)
            throws ParseException {
        String longTime = "";
        calendar = Calendar.getInstance();
        mDate = getDate(date, format);
        Calendar calen = Calendar.getInstance();
        calen.setTime(mDate);
        int year = calen.get(Calendar.YEAR);
        int month = calen.get(Calendar.MONTH);
        int dayOfMonth = calen.get(Calendar.DAY_OF_MONTH);
        int dayOfYear = calen.get(Calendar.DAY_OF_YEAR);
        int hour = calen.get(Calendar.HOUR_OF_DAY);
        int minute = calen.get(Calendar.MINUTE);
        long days = getDays(calen);
        if(days == 0){
            if(getHourOfDay() - hour == 0){
                if(getMinute() - minute == 0){
                    longTime = "刚刚";
                }else {
                    longTime = (getMinute() - minute) + "分钟前";
                }
            }else {
                if(getMinute()+(MINUTES_OF_HOUR-minute)+((getHourOfDay() - hour-1)*MINUTES_OF_HOUR) < MINUTES_OF_HOUR){
                    longTime = (getMinute()+(MINUTES_OF_HOUR-minute)) + "分钟前";
                }else {
                    longTime = (getHourOfDay() - hour) + "小时前";
                }
            }
        }else if(days < DAYS_OF_MONTH){
            longTime = days + "天前";
        }else if(days < DAYS_OF_YEAR && days >= DAYS_OF_MONTH){
            if(getYear() == year){
                longTime = (getMonth() - month) + "个月前";
            }else {
                longTime = (getMonth() + (MONTHES_OF_YEAR - month)) + "个月前";
            }

        }else {
            longTime = (getYear() - year) + "年前";
        }
        return longTime;
    }

    /**
    *获取两个日期之间相差多少天
    */
    public static int getDayBetween(String startTime,String todatTime){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(startTime));
            long time1 = cal.getTimeInMillis();
            cal.setTime(sdf.parse(todatTime));
            long time2 = cal.getTimeInMillis();
            //计算出相差月份是需要分清自然年
            long between_days=(time2-time1)/(1000*3600*24);
            return Integer.parseInt(between_days);
    }

    /**
     * 获取距当前的天数
     * 
     * @param calendar
     * @return
     */
    public static long getDays(Calendar calendar) {
        long days = 0;
        int year = calendar.get(Calendar.YEAR);
        int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
        if (year == getYear()) {
            days = getDayOfYear() - dayOfYear;
        } else {
            days = getDayOfYear()
                    + (((getYear() - year - 1) * DAYS_OF_YEAR) + (DAYS_OF_YEAR - dayOfYear));
        }
        return days;
    }

    /**
     * 获取时间
     * 
     * @param date
     * @param format
     * @return
     * @throws ParseException
     */
    public static Date getDate(String date, String format)
            throws ParseException {
        mDateFormat = new SimpleDateFormat(format);
        return mDateFormat.parse(date);
    }
    private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    private final static ThreadLocal<SimpleDateFormat> dateFormater2 = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd");
        }
    };
    /**
     * 将字符串转为日期类型
     * 
     * @param sdate
     * @return
     */
    public static Date toDate(String sdate) {
        try {
            return dateFormater.get().parse(sdate);
        } catch (ParseException e) {
            return null;
        }
    }
    /**
     * 以友好的方式显示时间
     * 
     * @param sdate
     * @return
     */
    public static String friendly_time(String sdate) {
        Date time = null;
        if (TimeZoneUtil.isInEasternEightZones()) {
            time = toDate(sdate);
        } else {
            time = TimeZoneUtil.transformTime(toDate(sdate),
                    TimeZone.getTimeZone("GMT+08"), TimeZone.getDefault());
        }
        if (time == null) {
            return "Unknown";
        }
        String ftime = "";
        Calendar cal = Calendar.getInstance();

        // 判断是否是同一天
        String curDate = dateFormater2.get().format(cal.getTime());
        String paramDate = dateFormater2.get().format(time);
        if (curDate.equals(paramDate)) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分钟前";
            else
                ftime = hour + "小时前";
            return ftime;
        }

        long lt = time.getTime() / 86400000;
        long ct = cal.getTimeInMillis() / 86400000;
        int days = (int) (ct - lt);
        if (days == 0) {
            int hour = (int) ((cal.getTimeInMillis() - time.getTime()) / 3600000);
            if (hour == 0)
                ftime = Math.max(
                        (cal.getTimeInMillis() - time.getTime()) / 60000, 1)
                        + "分钟前";
            else
                ftime = hour + "小时前";
        } else if (days == 1) {
            ftime = "昨天";
        } else if (days == 2) {
            ftime = "前天";
        } else if (days > 2 && days <= 10) {
            ftime = days + "天前";
        } else if (days > 10) {
            ftime = dateFormater2.get().format(time);
        }
        return ftime;
    }
    /**
     * 获取当前是周几
     * @return
     */
    public static String getWeek(){
        Calendar cal=Calendar.getInstance();
        int i=cal.get(Calendar.DAY_OF_WEEK);
        switch (i) {
            case 1:
                return "星期日";
            case 2:
                return "星期一";
            case 3:
                return "星期二";
            case 4:
                return "星期三";
            case 5:
                return "星期四";
            case 6:
                return "星期五";
            case 7:
                return "星期六";
            default:
                return "";
        }
    }
    /**
     * 根据日期获取星期
     * @param date
     * @return
     */
    public static String getWeekofDate(Date date){
           String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (w < 0)
                w = 0;
            return weekDays[w];
    }
    /**
     * 返回指定日期前几天的日期
     * @param date
     * @param day
     * @return
     */
    public static String getDayBefore(Date date,int day){
        Calendar now = Calendar.getInstance();
        String format="yyyy-MM-dd";
        mDateFormat=new SimpleDateFormat(format);
        try {
            date=mDateFormat.parse(getNow("dd"));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        now.setTime(date);  
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day); 
        format="dd";
        return mDateFormat.format(now.getTime()) ;  
    }
    /**
     * 返回指定日期后几天的日期
     * @param date
     * @param day
     * @return
     */
    public static String getDayAfter(Date date,int day){
       Calendar now = Calendar.getInstance();  
       String format="yyyy-MM-dd";
       mDateFormat=new SimpleDateFormat(format);
       try {
            date=mDateFormat.parse(getNow("dd"));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       now.setTime(date);  
       now.set(Calendar.DATE, now.get(Calendar.DATE) + day);  
       format="dd";
       return mDateFormat.format( now.getTime());  
    }

    /**
     * 返回几天前的日期
     * @param date
     * @param day
     * @return
     */
    public static Date getDateBefore(Date date,int day){
        Calendar now = Calendar.getInstance();  
        now.setTime(date);  
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);  
        return  now.getTime();  
    }
    /**
     * 返回几天后的日期
     * @param date
     * @param day
     * @return
     */
    public static Date getDateAfter(Date date,int day){
         Calendar now = Calendar.getInstance();  
       now.setTime(date);  
       now.set(Calendar.DATE, now.get(Calendar.DATE) + day);  
       return  now.getTime();  
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值