当前位置:首页 > 开发 > 编程语言 > Java > 正文

java时间加减 自己选合适的

发表于: 2011-12-01   作者:cooler1217   来源:转载   浏览:
摘要: public static String getBeforeDate(Date date,int days) { SimpleDateFormat df = new SimpleDateFormat(FORMAT_DAY); Calendar calendar = Calendar.getInstance(); calendar.setTime(date);
	public static String getBeforeDate(Date date,int days)
	{
		SimpleDateFormat df = new SimpleDateFormat(FORMAT_DAY);
		Calendar calendar = Calendar.getInstance();   
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_YEAR,calendar.get(Calendar.DAY_OF_YEAR) - days);
		return df.format(calendar.getTime());
	}
	
	public static String getAfterDate(Date date,int days)
	{
		SimpleDateFormat df = new SimpleDateFormat(FORMAT_DAY);
		Calendar calendar = Calendar.getInstance();   
		calendar.setTime(date);
		calendar.set(Calendar.DAY_OF_YEAR,calendar.get(Calendar.DAY_OF_YEAR) + days);
		return df.format(calendar.getTime());
	}


	public static String getBeforeDate(Date date,int days)
	{
		SimpleDateFormat df = new SimpleDateFormat(FORMAT_DAY);
		Date beforeDate = new Date(date.getTime() - days * 24 * 60 * 60 * 1000);
		return df.format(beforeDate);
	}
	
	public static String getAfterDate(Date date,int days)
	{
		SimpleDateFormat df = new SimpleDateFormat(FORMAT_DAY);
		Date beforeDate = new Date(date.getTime() + days * 24 * 60 * 60 * 1000);
		return df.format(beforeDate);
	}


DateFormat df=new SimpleDateFormat("yyyy-MM-dd EE hh:mm:ss"); 
System.out.println(df.format(new Date())); 
Date date = new Date(); 
DateFormat shortDate=DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); 
DateFormat mediumDate =DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); 
DateFormat longDate =DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); 
DateFormat fullDate =DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL); 

system.out.println(shortDate.format(date)); 
System.out.println(mediumDate.format(date)); 
System.out.println(longDate.format(date)); 
System.out.println(fullDate.format(date)); 

08-4-15 下午3:24 
2008-4-15 15:24:31 
2008年4月15日 下午03时24分31秒 
2008年4月15日 星期二 下午03时24分31秒CST 


Calendar c = Calendar.getInstance(); 

c.add(Calendar.MONTH, 1); // 目前時間加1個月 
System.out.println(df.format(c.getTime())); 

c.add(Calendar.HOUR, 3); // 目前時間加3小時 
System.out.println(df.format(c.getTime())); 

c.add(Calendar.YEAR, -2); // 目前時間減2年 
System.out.println(df.format(c.getTime())); 

c.add(Calendar.DAY_OF_WEEK, 7); // 目前的時間加7天 
System.out.println(df.format(c.getTime())); 

java时间加减 自己选合适的

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号