2012-08-26
package com.sxito.biz.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
*
* @author 落叶
*
*/
public class TestStringToDate {
/**
* @param args
*/
public static void main(String[] args) {
String s1 = "1991-01-01";
StringToDate(s1);
Date d =new Date();
DateToString(d);
Calendar calendar= DateToCalendar(d);
CalendarToDate(calendar);
}
/**
* 字符串转日期
* @param String
*/
private static Date StringToDate(String String) {
System.out.println("转换前类型为:"+String.getClass());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date time = null;
try {
time = format.parse(String);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("转换后类型为:"+time.getClass());
return time;
}
/**
* 日期转换成字符串
* @param date
* @return str
*/
public static String DateToString(Date date) {
System.out.println("转换前类型为:"+date.getClass());
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = format.format(date);
System.out.println("转换后类型为:"+string.getClass());
return string;
}
/**
* 日期转日历
* @param date
* @return Calendar
*/
public static Calendar DateToCalendar(Date date) {
System.out.println("转换前类型为:"+date.getClass());
Calendar startdate=Calendar.getInstance();
startdate.setTime(date);
System.out.println("转换后类型为:"+startdate.getClass());
return startdate;
}
/**
* 日历转日期
* @param calendar
* @return Date
*/
public static Date CalendarToDate(Calendar calendar) {
System.out.println("转换前类型为:"+calendar.getClass());
Date date= calendar.getTime();
System.out.println("转换后类型为:"+date.getClass());
return date;
}
}