Java日期计算
来源:互联网 发布:淘宝快捷方式下载 编辑:程序博客网 时间:2024/05/18 08:58
Java中提供了丰富的日期表示方式。其中包括Date、Timestamp、Calendar、GregorianCalendar类。GregorianCalendar类中提供了用于计算日期的add()方法,可以很方便地计算若干年、月、日后的日期。
给个例子看看:
package testjava;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
public class DateTest {
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateTest test = new DateTest();
//Date
Date currentDate = new Date();
System.out.println("当前日期是:" + df.format(currentDate));
System.out.println("一周后的日期是:" + df.format(test.nextWeek(currentDate)));
System.out.println("一月后的日期是:" + df.format(test.nextMonth(currentDate)));
System.out.println("一年后的日期是:" + df.format(test.nextYear(currentDate)));
//Timestamp
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
System.out.println("当前日期是:" + df.format(currentTime));
System.out.println("一周后的日期是:" + df.format(test.nextWeek(currentTime)));
System.out.println("一月后的日期是:" + df.format(test.nextMonth(currentTime)));
System.out.println("一年后的日期是:" + df.format(test.nextYear(currentTime)));
//另一种计算方式,这种方式计算月和年的日期比较困难
Timestamp nextTime = new Timestamp(currentTime.getTime() + 7 * 24 * 60 * 60 * 1000);
System.out.println("当前日期是:" + df.format(currentTime));
System.out.println("一周后的日期是:" + df.format(nextTime));
}
//获取下一周的日期
public Date nextWeek(Date currentDate) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(currentDate);
cal.add(GregorianCalendar.DATE, 7);//在日期上加7天
return cal.getTime();
}
//获取本周日的日期
public Date getSunday(Date monday) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(monday);
cal.add(GregorianCalendar.DATE, 6);//在日期上加6天
return cal.getTime();
}
//获取下一月的日期
public Date nextMonth(Date currentDate) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(currentDate);
cal.add(GregorianCalendar.MONTH, 1);//在月份上加1
return cal.getTime();
}
//获取下一年的日期
public Date nextYear(Date currentDate) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(currentDate);
cal.add(GregorianCalendar.YEAR, 1);//在年上加1
return cal.getTime();
}
}
- java日期 计算前后日期
- 计算Java日期
- Java日期计算
- 计算Java日期
- 计算Java日期
- 计算Java日期
- [转载]计算Java日期
- 计算Java日期
- 计算Java日期
- 计算Java日期
- 计算Java日期
- 计算Java日期
- java日期计算
- 计算Java日期
- 计算Java日期
- Java日期计算
- 计算Java日期
- JAVA 日期比较、计算
- 记住“迷茫总在未见其全貌时”
- plantix
- Installation failed for component Windows Mobile 5.0 SDK R2 for Pocket PC. MSI returned error code
- MFC中CListCtrl的排序 简介
- 关于ASP.NET中配置上传文件限制
- Java日期计算
- 使用 GDB 调试多进程程序
- Java Web项目开发到底需要掌握哪些技术?
- 如何查看SQL Server版本号
- Oracle新建用户,授权,建表空间(转)
- 共享内存进一步学习
- 系统登陆就注销的解决方法
- 向左走向右走
- sda.fill(a,b)到底是啥意思?