标签:日期 res == 解析 ring format pac ted settime
Date类与Calendar类之间的转换
1 package date; 2 3 import java.util.Calendar; 4 import java.util.Date; 5 6 public class DateDemo { 7 8 public static void main(String[] args) { 9 /** 10 * 可以直接输出Date,不可以直接输出Calendar 11 * 已知当前Date类的日期now,Calendar类的日期calendar, 12 * 1.将Date--->Calendar,用calendar.setTime(now); 13 * 2.将Calendar--->Date,那么now=calendar.getTime(); 14 */ 15 Date now=new Date(); 16 Calendar calendar=Calendar.getInstance(); 17 long now1=System.currentTimeMillis(); 18 long now2=now.getTime(); 19 long now3=calendar.getTimeInMillis(); 20 System.out.println("now :"+now); 21 System.out.println("calendar.Year :"+calendar.get(Calendar.YEAR)); 22 System.out.println("now1 :"+now1); 23 System.out.println("now2 :"+now2); 24 System.out.println("now3 :"+now3); 25 26 calendar.add(Calendar.YEAR,-19); 27 System.out.printf("%d-%d-%d\n",calendar.get(Calendar.YEAR), 28 calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)); 29 //Date-->Calendar 30 Calendar c1=Calendar.getInstance();//调用Calendar类中的静态方法getInstance()来得到一个Calendar对象 31 c1.setTime(now); 32 33 //Calendar-->Date 34 Date birth=calendar.getTime(); 35 System.out.println("birth :"+birth); 36 37 System.out.println(birth.toLocaleString()); 38 39 } 40 41 }
输出如下内容:
now :Sun Dec 30 11:32:57 CST 2018
calendar.Year :2018
now1 :1546140777528
now2 :1546140777390
now3 :1546140777468
1999-11-30
birth :Thu Dec 30 11:32:57 CST 1999
1999-12-30 11:32:57
DateFormat类:
1 package date; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.Calendar; 6 import java.util.Date; 7 import java.util.Locale; 8 9 public class DateFormatDemo { 10 11 public static void main(String[] args) { 12 Date now = new Date(); 13 14 // Date ==> Calendar 15 Calendar calendar = Calendar.getInstance(); 16 calendar.setTime(now); 17 18 // 加8周 19 calendar.add(Calendar.WEEK_OF_YEAR, 8); 20 21 // Calendar ==> Date 22 now = calendar.getTime(); 23 System.out.println(now); 24 25 // 格式化 26 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", 27 28 Locale.CHINA); 29 // Date ==> String 30 String result = format.format(now);//format为DateFormat类中的一个方法,用于Formats a Date into a date/time string. 31 System.out.println(result); 32 33 // String ==> Date 34 String d = "2018-01-12 09:21:21.000"; 35 try { 36 Date date = format.parse(d);//parse解析,也是DateFormat类中的一个方法,解析给定字符串中的文本内容,以产生一个日期 37 System.out.println(date); 38 } catch (ParseException e) { 39 e.printStackTrace(); 40 } 41 42 } 43 }
标签:日期 res == 解析 ring format pac ted settime
原文地址:https://www.cnblogs.com/LJHAHA/p/10198923.html