Java日期转换

伊谢尔伦
伊谢尔伦 原创
2016-12-05 13:47:37 1161浏览

涉及的核心类:Date类、SimpleDateFormat类、Calendar类

一、 Date型与long型

Date型转换为long型
Date date = new Date();//取得当前时间Date类型

long date2long = date.getTime();//Date转long

long型转换为Date型
long cur = System.currentTimeMills();//取得当前时间long型返回

Date long2date = new Date(cur);//long转Date

二、Date型与String型

Date型转换为String型
Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”);//设置目标转换格式为yyyy-MM-dd HH:mm:ss.SSS

String date2string = sdf.format(date);//Date转String

String型转换为Date型
String str=”2001-11-03 11:12:33.828”;//设置初始string类型日期

Date str2date=sdf.parse(str);//String转Date

三、Date型与Calendar型

Date型转换为Calendar型
Calendar cal = Calendar.getInstance();//取得当前时间Calendar类型

cal.setTime(date); //Date转Calendar

Calendar型转换为Date型
Calendar cal = Calendar.getInstance();//取得当前时间Calendar类型

Date cal2date = cal.getTime();//Calendar转Date

四、总结

String与基本类型之间的转换依靠的是String.valueOf()方法
Date与String类之间的转换依靠的是SimpleDateFormat类
Date与long转换依靠的是Date提供的构造以及getTime()方法
Date与Calendar转换依靠的是Calendar提供的setTime()及getTime()方法
五、面试题

Q:写一个方法,参数是Date date,将date往后推3天,在以“yyyy-mm-dd”格式返回字符串类型

public String add3Day(Date date) throws ParseException{
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);//Date转换为Calendar
   cal.add(Calendar.DATE, 3);//将日期往后推3天,减少3天则-3. 月增加则Calendar.MONTH
   String after = sdf.format(cal.getTime());//Calendar转换为Date,再转换为String
   return after;
}


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。