---
title: "java日期计算"
author: "charles751"
date: "2010-05-26T14:45:26Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2011-08-03T15:19:30Z"
id: 675942
url: "https://qify.iteye.com/blog/675942"
---

Calendar类:一个抽像类，不能直接new 得到。  
Calendar C = Calendar.getInstance();// 得到当前时间  
C.add(C.DATE, 5);//在当前的日期上加上5天  
一般可以转化为util包的Date类  
java.util.Date temp\_date = C.getTime();  
这样就可以对日期进行操作了.

 

代码示例：

01. **public** **class** DateTest {
02. **public** **static** **void** main(String\[] args) {
03. Date date = **new** Date(); // 新建一个日期
04. SimpleDateFormat sdf = **new** SimpleDateFormat("yyyy-MM-dd"); // 格式化日期
05. String beforeDate = sdf.format(getDateBefore(date, 10));
06. System.out.println(beforeDate);
07. String afterDate = sdf.format(getDateAfter(date, 10));
08. System.out.println(afterDate);
09. }
10. /\**
11. * 得到几天前的时间
12. \*/
13. **public** **static** Date getDateBefore(Date d, **int** day) {
14. Calendar now = Calendar.getInstance();
15. now.setTime(d);
16. now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
17. **return** now.getTime();
18. }
19. /\**
20. * 得到几天后的时间
21. \*/
22. **public** **static** Date getDateAfter(Date d, **int** day) {
23. Calendar now = Calendar.getInstance();
24. now.setTime(d);
25. now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
26. **return** now.getTime();
27. }
28. }

 

http://moppet.taobao.com/