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

四、总结

 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;
 }

文档来源:http://www.cnblogs.com/Hugooscar/p/6026173.html

Java中日期格式和其他类型转换详解编程语言

转载请注明来源网站:blog.ytso.com谢谢!

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/14741.html

(0)
上一篇 2021年7月19日 17:05
下一篇 2021年7月19日 17:05

相关推荐

发表回复

登录后才能评论