日期工具类DateUtils

package date.util;

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

public class DateUtils {
	
	static final String formatPattern = "yyyy-MM-dd";
	
	static final String formatPattern_Short = "yyyyMMdd";
	
	
	/**
	 * 获取当前日期
	 * @return
	 */
	public static String getCurrentDate(){
		SimpleDateFormat format = new SimpleDateFormat(formatPattern);		
		return format.format(new Date());
	}
	
	/**
	 * 获取制定毫秒数之前的日期
	 * @param timeDiff
	 * @return
	 */
	public static String getDesignatedDate(long timeDiff){
		SimpleDateFormat format = new SimpleDateFormat(formatPattern);
		long nowTime = System.currentTimeMillis();
		long designTime = nowTime - timeDiff;		
		return format.format(designTime);
	}
	
	/**
	 * 
	 * 获取前几天的日期
	 */
	public static String getPrefixDate(String count){
		Calendar cal = Calendar.getInstance();
		int day = 0-Integer.parseInt(count);
		cal.add(Calendar.DATE,day);   // int amount   代表天数
		Date datNew = cal.getTime(); 
		SimpleDateFormat format = new SimpleDateFormat(formatPattern);
		return format.format(datNew);
	}
	/**
	 * 日期转换成字符串
	 * @param date
	 * @return
	 */
	public static String dateToString(Date date){
		SimpleDateFormat format = new SimpleDateFormat(formatPattern);
		return format.format(date);
	}
	/**
	 * 字符串转换日期
	 * @param str
	 * @return
	 */
	public static Date stringToDate(String str){
		//str =  " 2008-07-10 19:20:00 " 格式
		SimpleDateFormat format = new SimpleDateFormat(formatPattern);
		if(!str.equals("")&&str!=null){
			try {
				return format.parse(str);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
	
	//java中怎样计算两个时间如:“21:57”和“08:20”相差的分钟数、小时数 java计算两个时间差小时 分钟 秒 .
	public void timeSubtract(){
		SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		Date begin = null; 
		Date end = null; 
		try { 
		begin = dfs.parse("2004-01-02 11:30:24"); 
		end = dfs.parse("2004-03-26 13:31:40"); 
		} catch (ParseException e) { 
		e.printStackTrace(); 
		} 

		long between = (end.getTime() - begin.getTime()) / 1000;// 除以1000是为了转换成秒 

		long day1 = between / (24 * 3600); 
		long hour1 = between % (24 * 3600) / 3600; 
		long minute1 = between % 3600 / 60; 
		long second1 = between % 60; 
		System.out.println("" + day1 + "天" + hour1 + "小时" + minute1 + "分" 
		+ second1 + "秒"); 
	}

}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值