Java日期时间操作的一些方法

String datetime = sdf.format(c.getTime());

4. 把字符串转换成日期/时间,使用SimpleDateFormat的parse()方法:

Date d = sdf3.parse("2016-08-08 16:43:00");

5. 日期/时间的增加,减少,使用Calendar的add()方法,如将日期减少100天:

c.add(Calendar.DATE, -100);

6. 日期/时间的设置,使用Calendar的set()方法,如将小时设置为0时:

c.set(Calendar.HOUR_OF_DAY, 0);

例子:

package myCalendar; import Java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class myCalendar { public static void main(String args[]) throws Exception{ Calendar c = Calendar.getInstance(); SimpleDateFormat sdf1 =new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat sdf2 =new SimpleDateFormat("HHmmss"); SimpleDateFormat sdf3 =new SimpleDateFormat("yyyyMMddHHmmss"); SimpleDateFormat sdf4 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = sdf1.format(c.getTime()); System.out.println(date); String time = sdf2.format(c.getTime()); System.out.println(time); String dt = "20160808162405"; Date d = sdf3.parse(dt); dt = sdf4.format(d); c.setTime(d); c.add(Calendar.DATE, -100); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); System.out.println("100天前:" + sdf4.format(c.getTime())); c.add(Calendar.DATE, 200); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); System.out.println("100天后:" + sdf4.format(c.getTime())); } }

运行结果如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/d563af12b0cbf9d23471a8d87bf41c05.html