Java 日期转换详解及实例代码
Java 日期转换 涉及的核心类: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 四、总结
五、面试题 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; } 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |