1.String、Date、Calendar之间的转换
要用到格式化类SimpleDateFormat
1 package com.rong.se; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.Calendar; 6 import java.util.Date; 7 8 public class StringDate { 9 10 public static void main(String[] args) { 11 // 格式化对象 12 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 13 // SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 14 // ///////////////////////////////////////////////////// 15 // SimpleDateFormat sdf=new SimpleDateFormat(); 16 // sdf.applyPattern("yyyy-MM-dd hh:mm:ss"); 17 18 try { 19 // String类型转换为Date类型 20 String string = "2017-11-11 20:20:20"; 21 Date date = sdf.parse(string); 22 System.out.println(date); 23 24 } catch (ParseException e) { 25 e.printStackTrace(); 26 } 27 28 // Date类型转换为String类型 29 Date date = new Date(); 30 String format = sdf.format(date); 31 System.out.println(format); 32 33 // Calendar类型转换为Date类型 34 Calendar calendar = Calendar.getInstance(); 35 Date cDate = calendar.getTime(); 36 System.out.println(cDate); 37 38 // Date类型转换为Calendar类型 39 try { 40 String string = "1995-09-24 13:14:03"; 41 Date parse = sdf.parse(string); 42 // /////////////////////////////////// 43 calendar.setTime(parse); 44 // 获取年份 45 System.out.println(calendar.get(Calendar.YEAR)); 46 47 } catch (ParseException e) { 48 e.printStackTrace(); 49 } 50 // String类型转换为Calendar类型 51 try { 52 String str = "2002-01-01 18:30:00"; 53 Date parse = sdf.parse(str); 54 Calendar instance = Calendar.getInstance(); 55 instance.setTime(parse); 56 System.out.println(instance.get(Calendar.YEAR)); 57 } catch (ParseException e) { 58 e.printStackTrace(); 59 } 60 // Calendar类型转换为String类型 61 Calendar instance = Calendar.getInstance(); 62 Date time = instance.getTime(); 63 String string = sdf.format(time); 64 System.out.println(string); 65 66 } 67 68 }