涉及的核心类: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;
}
五、总结
String与基本类型之间的转换依靠的是String.valueOf()方法
Date与String类之间的转换依靠的是SimpleDateFormat类
Date与long转换依靠的是Date提供的构造以及getTime()方法
Date与Calendar转换依靠的是Calendar提供的setTime()及getTime()方法

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Atom编辑器mac版下载
最流行的的开源编辑器

Dreamweaver CS6
视觉化网页开发工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能