当前位置:学者斋 >

计算机 >java语言 >

java日期时间基本操作方法

java日期时间基本操作方法

1. 获得Calendar实例:Calendar c = nstance();

java日期时间基本操作方法

2. 定义日期/时间的格式:SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

3. 把日期/时间转换成固定格式,使用SimpleDateFormat的'format()方法:

String datetime = at(ime());

4. 把字符串转换成日期/时间,使用SimpleDateFormat的parse()方法:Date d = e("2016-08-08 16:43:00");

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

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

(_OF_DAY, 0);

例子:

package myCalendar;import eException;import leDateFormat;import ndar;import ;public class myCalendar { public static void main(String args[]) throws Exception{ Calendar c = nstance(); 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 = at(ime()); tln(date); String time = at(ime()); tln(time); String dt = "20160808162405"; Date d = e(dt); dt = at(d); ime(d); (, -100); (_OF_DAY, 0); (TE, 0); (ND, 0); tln("100天前:" + at(ime())); (, 200); (_OF_DAY, 0); (TE, 0); (ND, 0); tln("100天后:" + at(ime())); }}

  • 文章版权属于文章作者所有,转载请注明 https://xuezhezhai.com/jsj/java/n1xjzm.html