首页 > 代码库 > 【java】Date与String之间的转换:java.text.SimpleDateFormat、public Date parse(String source) throws ParseException和public final String format(Date date)
【java】Date与String之间的转换:java.text.SimpleDateFormat、public Date parse(String source) throws ParseException和public final String format(Date date)
1 package 日期日历类; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 public class TestDate { 8 public static void main(String[] args) { 9 Date date=new java.util.Date(); 10 System.out.println(date);//Fri Apr 07 22:20:12 CST 2017 11 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 12 String d=sdf.format(date); 13 System.out.println(d);//2017-04-07 22:20:12 14 String d2="2017-04-06 12:30:30"; 15 Date date2=new Date(); 16 try { 17 date2 = sdf.parse(d2); 18 } catch (ParseException e) { 19 e.printStackTrace(); 20 } 21 System.out.println(date2);//Thu Apr 06 12:30:30 CST 2017 22 } 23 }
java.lang.Object
java.text.Format
java.text.DateFormat ->public Date parse(String source) throws ParseException和public final String format(Date date)
java.text.SimpleDateFormat
1 package 日期日历类; 2 3 import java.util.Calendar; 4 import java.util.Date; 5 6 public class TestDate { 7 public static void main(String[] args) { 8 Date date=new java.util.Date(); 9 System.out.println(date);//Fri Apr 07 22:53:21 CST 2017 10 Calendar cal=Calendar.getInstance(); 11 System.out.println(cal);//java.util.GregorianCalendar[time=1491576801409,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2017,MONTH=3,WEEK_OF_YEAR=14,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=97,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MINUTE=53,SECOND=21,MILLISECOND=409,ZONE_OFFSET=28800000,DST_OFFSET=0] 12 Date date2=cal.getTime();//Calendar转为Date 13 System.out.println(date2);//Fri Apr 07 22:53:21 CST 2017 14 StringBuffer sb=new StringBuffer(); 15 16 //月份从0开始算,所以要加1 17 sb.append(cal.get(Calendar.YEAR)).append("年").append(cal.get(Calendar.MONTH)+1).append("月").append(cal.get(Calendar.DAY_OF_MONTH)).append("日").append(cal.get(Calendar.HOUR_OF_DAY)).append(":").append(cal.get(Calendar.MINUTE)).append(":").append(cal.get(Calendar.SECOND)); 18 System.out.println(sb);//2017年4月7日22:53:21 19 } 20 }
【java】Date与String之间的转换:java.text.SimpleDateFormat、public Date parse(String source) throws ParseException和public final String format(Date date)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。