java 时间运算_java日期时间的运算

Java日期时间运算经常会在程序中被用到。以前楼主用到的时候会自己处理时间后进行加减运算 (yy-MM-dd 去掉-后转成int进行运算,呵呵。),现在想来,无疑这种方法不太合适。

无所不能的Java提供了强大的工具类:java.util.Date和java.util.Calendar.

直接来个小例子吧。

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

public class JavaDateOperation{

//定义时间格式

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

Date date = new Date();

//输出当前时间

System.out.println("now:"+format.format(date));

//获得Calendar实例

Calendar calendar = Calendar.getInstance();

//把要进行运算的时间放到calendar实例中

calendar.setTime(date);

//进行运算

//去年

calendar.add(Calendar.YEAR,-1);

System.out.println("last year:"+format.format(calendar.getTime()));

//下个月

calendar.setTime(date);

calendar.add(Calendar.Month,1);

System.out.println("next month:"+format.format(calendar.getTime()));

}

同理,上月,下周的都一样获得。

另外,Calendar类很是强大,这上面就列举了最基本的应用,还有像:

System.out.println("the week of this month is" + calendar.get(Calendar.WEEK_OF_MONTH));//本月第几周

System.out.println("the week of this yeah is" + calendar.get(Calendar.WEEK_OF_YEAR));//本年第几周

等等。总之,Calendar类是很强大的。

抛砖引玉,如有不当,请加以指正。如需讨论请留言或者加QQ:70747053

原创,转载请注明出处。谢谢。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值