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
原创,转载请注明出处。谢谢。