java 时间操作

来源:互联网 发布:java简明教程 pdf 编辑:程序博客网 时间:2024/05/29 08:04

java 时间操作

1。计算时间间隔
GregorianCalendar gc1 = new GregorianCalendar(1995, 11, 1, 3, 2, 1);
GregorianCalendar gc2 = new GregorianCalendar(1995, 11, 1, 3, 2, 2);
//the above two dates are one second apart
Date d1 = gc1.getTime();
Date d2 = gc2.getTime();
long l1 = d1.getTime();//返回从1970年1月1日到这个时间的long类型的毫秒数值
long l2 = d2.getTime();
long difference = l2 - l1;
System.out.println("Elapsed milliseconds: " + difference);

2。计算当前系统运行所花费的时间
long startTime = System.currentTimeMillis();
long endTime = System.currentTimeMillis();

long costTime=entTime-startTime;

3。文本日期转Date对象
GregorianCalendar liftOffApollo11 = new GregorianCalendar(1969, Calendar.JULY, 16, 9, 32);
Date d = liftOffApollo11.getTime();

4。指定显示的方式(格式化日期和时间)
Date d = liftOffApollo11.getTime();
DateFormat df1 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
String s1 = df1.format(d);

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String szDatetime1 = df.format(utilDate);

 

5。计算两个日期之间的天数和月数
 java.util.Date date2 = new java.util.Date(nCurrentTime - 24600 * 1000);

 long nMilliSeconds = utilDate.getTime() - date2.getTime();
 long nSeconds =? nMilliSeconds / 1000;? //把毫秒换算成秒
 double nDays = nSeconds / (24d * 60d * 60d);? //把秒换算成天

 String szDatetime2 = df.format(date2);
 System.out.println("Time between " + szDatetime1 + " and " + szDatetime2 + " is " + nSeconds + " seconds (" + nDays + " days)");


6。用于获取指定的时间项(字段)
long nCurrentTime = System.currentTimeMillis();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(nCurrentTime);

int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;?? //注意:返回的月份是基于0的!
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

System.out.println("Current date is: " + year + "年" + month + "月" + day + "日");
System.out.println("Current time is: " + hour + "时" + minute + "分" + second + "秒");
 

原创粉丝点击