1.String、Date、Calendar之间的转换
要用到格式化类SimpleDateFormat
package com.rong.se; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date; public class StringDate { public static void main(String[] args) {
// 格式化对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// /////////////////////////////////////////////////////
// SimpleDateFormat sdf=new SimpleDateFormat();
// sdf.applyPattern("yyyy-MM-dd hh:mm:ss"); try {
// String类型转换为Date类型
String string = "2017-11-11 20:20:20";
Date date = sdf.parse(string);
System.out.println(date); } catch (ParseException e) {
e.printStackTrace();
} // Date类型转换为String类型
Date date = new Date();
String format = sdf.format(date);
System.out.println(format); // Calendar类型转换为Date类型
Calendar calendar = Calendar.getInstance();
Date cDate = calendar.getTime();
System.out.println(cDate); // Date类型转换为Calendar类型
try {
String string = "1995-09-24 13:14:03";
Date parse = sdf.parse(string);
// ///////////////////////////////////
calendar.setTime(parse);
// 获取年份
System.out.println(calendar.get(Calendar.YEAR)); } catch (ParseException e) {
e.printStackTrace();
}
// String类型转换为Calendar类型
try {
String str = "2002-01-01 18:30:00";
Date parse = sdf.parse(str);
Calendar instance = Calendar.getInstance();
instance.setTime(parse);
System.out.println(instance.get(Calendar.YEAR));
} catch (ParseException e) {
e.printStackTrace();
}
// Calendar类型转换为String类型
Calendar instance = Calendar.getInstance();
Date time = instance.getTime();
String string = sdf.format(time);
System.out.println(string); } }