android日期时间工具

在开发过程中,对时间的操作是不可避免的,记录一些封装的时间工具:

1.近多少天,比如:近7天,近30天之类的:

 /**
     * 近多少天
     * @param date_end  String类的时间
     * @param dur 天数,可正负,
     * @return
     */
    public  static String getNearlyDate(String date_end,long dur){
        DateFormat df = null;
        df = new SimpleDateFormat("yyyy-MM-dd");
        long diff = 0;
        try {
            Date d2 = df.parse(date_end);
            diff = d2.getTime() - (dur*(1000 * 60 * 60 * 24));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return getDateTimeFromMillisecond(diff);
    }

2.时间间隔,比大小,相差多少天

 /**
     * 时间间隔,时间比大小,相差多少天
     * @param date_begin 开始时间
     * @param date_end  结束时间
     * @param type 时间格式类型
     * @return
     */
    public  static long getDateSpan(String date_begin,String date_end,int type){
        DateFormat df = null;
        if(type==0){
            df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }else if(type==1){
            df = new SimpleDateFormat("yyyy-MM-dd");
        }
        long days = 0;
        try {
            Date d1 = df.parse(date_begin);
            Date d2 = df.parse(date_end);
            long diff = d2.getTime() - d1.getTime();
            days = diff / (1000 * 60 * 60 * 24);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

3.毫秒转固定时间格式

 /**
     * 毫秒转固定时间格式,android是13位
     * @param millisecond
     * @return
     */
    public static String getDateTimeFromMillisecond(Long millisecond){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(millisecond);
        String dateStr = simpleDateFormat.format(date);
        return dateStr;
    }

4.获取当前系统时间

 /**
     * 获取当前系统时间
     * @param type 时间格式类型
     * @return
     */
    public  static String getCurDate(int type){
        SimpleDateFormat sDateFormat = null;
        if(type==1){
            sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }else if(type==2){
            sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        }else if(type==3){
            sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        }
        String date = sDateFormat.format(new java.util.Date());
        return date;
    }

5.日期,时间搓显示:

 /**
     * 日期和时间搓
     * isShowTime:true 是否显示具体时间
     */
    private static Calendar dateAndTime=Calendar.getInstance(Locale.CHINA);
    private static DateFormat fmtDate=new java.text.SimpleDateFormat("yyyy-MM-dd");
    private static DateFormat fmtTime=new java.text.SimpleDateFormat("HH:mm:ss");
    public static void runTime(final Context context, final TextView mEditText, final boolean isShowTime) {
        //时间搓
            final TimePickerDialog.OnTimeSetListener t=new TimePickerDialog.OnTimeSetListener() {

                @Override
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    dateAndTime.set(Calendar.HOUR_OF_DAY,hourOfDay);
                    dateAndTime.set(Calendar.MINUTE, minute);
                    mEditText.setText(fmtDate.format(dateAndTime.getTime())+" "+fmtTime.format(dateAndTime.getTime()));
                }
            };
        //日期搓
        final DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                dateAndTime.set(Calendar.YEAR,year);
                dateAndTime.set(Calendar.MONTH, monthOfYear);
                dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                if(!isShowTime){
                    if( getDateSpan(getCurDate(3),fmtDate.format(dateAndTime.getTime()),1)<0){
                            ToastUtils.showToast(context,"时间不能小于当前时间");
                        return;
                    }
                    mEditText.setText(fmtDate.format(dateAndTime.getTime()));
                }

            }
        };
        //时间搓显示
        TimePickerDialog mTimePickerDialog=new TimePickerDialog(context, t, dateAndTime.get(Calendar.HOUR_OF_DAY),
                dateAndTime.get(Calendar.MINUTE), true);
        if(isShowTime){//判断是是显示时间搓,可用于只显示日期
            mTimePickerDialog.show();
        }
        //日期搓显示
        DatePickerDialog mDatePickerDialog=new DatePickerDialog(context, d, dateAndTime.get(Calendar.YEAR),
                dateAndTime.get(Calendar.MONTH), dateAndTime.get(Calendar.DAY_OF_MONTH));
        mDatePickerDialog.show();
    }

6.多少时间之前:

/**
	 * 以友好的方式显示时间
	 *多少时间之前
	 * @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 < 31) {
			ftime = days + "天前";
		} else if (days >= 31 && days <= 2 * 31) {
			ftime = "一个月前";
		} else if (days > 2 * 31 && days <= 3 * 31) {
			ftime = "2个月前";
		} else if (days > 3 * 31 && days <= 4 * 31) {
			ftime = "3个月前";
		} else {
			ftime = dateFormater2.get().format(time);
		}
		return ftime;
	}

7.判断当前时间是星期几

/**
	 * 判断当前时间是星期几
	 * @param sdate
     * @return
     */
	public static String friendly_time2(String sdate) {
		String res = "";
		if (StringUtils.isEmpty(sdate))
			return "";

		String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		String currentData = StringUtils.getDataTime("MM-dd");
		int currentDay = StringUtils.toInt(currentData.substring(3));
		int currentMoth = StringUtils.toInt(currentData.substring(0, 2));

		int sMoth = StringUtils.toInt(sdate.substring(5, 7));
		int sDay = StringUtils.toInt(sdate.substring(8, 10));
		int sYear = StringUtils.toInt(sdate.substring(0, 4));
		Date dt = new Date(sYear, sMoth - 1, sDay - 1);

		if (sDay == currentDay && sMoth == currentMoth) {
//			res = "今天 / " + weekDays[getWeekOfDate(new Date())];
			res = weekDays[getWeekOfDate(new Date())];
		} else if (sDay == currentDay + 1 && sMoth == currentMoth) {
//			res = "昨天 / " + weekDays[(getWeekOfDate(new Date()) + 6) % 7];
			res =  weekDays[(getWeekOfDate(new Date()) + 6) % 7];
		} else {
			if (sMoth < 10) {
				res = "0";
			}
			res += sMoth + "/";
			if (sDay < 10) {
				res += "0";
			}
//			res += sDay + " / " + weekDays[getWeekOfDate(dt)];
			res= weekDays[getWeekOfDate(dt)];
		}

		return res;
	}

8.判断一个时间是不是上午:

/**
	 * @return 判断一个时间是不是上午
	 */
	public static boolean isMorning(long when) {
		android.text.format.Time time = new android.text.format.Time();
		time.set(when);

		int hour = time.hour;
		return (hour >= 0) && (hour < 12);
	}

9.判断一个时间是不是今天:

/**
	 * @return 判断一个时间是不是今天
	 */
	public static boolean isToday(long when) {
		android.text.format.Time time = new android.text.format.Time();
		time.set(when);

		int thenYear = time.year;
		int thenMonth = time.month;
		int thenMonthDay = time.monthDay;

		time.set(System.currentTimeMillis());
		return (thenYear == time.year)
				&& (thenMonth == time.month)
				&& (thenMonthDay == time.monthDay);
	}

10.判断一个时间是不是昨天:

/**
	 * @return 判断一个时间是不是昨天
	 */
	public static boolean isYesterday(long when) {
		android.text.format.Time time = new android.text.format.Time();
		time.set(when);

		int thenYear = time.year;
		int thenMonth = time.month;
		int thenMonthDay = time.monthDay;

		time.set(System.currentTimeMillis());
		return (thenYear == time.year)
				&& (thenMonth == time.month)
				&& (time.monthDay - thenMonthDay == 1);
	}

11.判断一个时间是不是今年:

/**
	 * @return 判断一个时间是不是今年
	 */
	public static boolean isCurrentYear(long when) {
		android.text.format.Time time = new android.text.format.Time();
		time.set(when);

		int thenYear = time.year;

		time.set(System.currentTimeMillis());
		return (thenYear == time.year);
	}

12.智能格式化时间:

/**
	 * 智能格式化
	 */
	public static String friendly_time3(String sdate) {
		String res = "";
		if (StringUtils.isEmpty(sdate))
			return "";

		Date date = StringUtils.toDate(sdate);
		if (date == null)
			return sdate;

		SimpleDateFormat format = dateFormater2.get();

		if (isToday(date.getTime())) {
			format.applyPattern(isMorning(date.getTime()) ? "上午 hh:mm" : "下午 hh:mm");
			res = format.format(date);
		} else if (isYesterday(date.getTime())) {
			format.applyPattern(isMorning(date.getTime()) ? "昨天 上午 hh:mm" : "昨天 下午 hh:mm");
			res = format.format(date);
		} else if (isCurrentYear(date.getTime())) {
			format.applyPattern(isMorning(date.getTime()) ? "MM-dd 上午 hh:mm" : "MM-dd 下午 hh:mm");
			res = format.format(date);
		} else {
			format.applyPattern(isMorning(date.getTime()) ? "yyyy-MM-dd 上午 hh:mm" : "yyyy-MM-dd 下午 hh:mm");
			res = format.format(date);
		}
		return res;
	}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值