date日期类型与String类型的相互转化
Code:
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import org.apache.log4j.Logger;
- import com.fourstar.log4j.HelloLog4j;
- public class DateUtil {
- private static final Logger log = Logger.getLogger(HelloLog4j.class);//获得当前类
- public static Date toDate(String dateStr) {
- Date date = null;
- SimpleDateFormat formater = new SimpleDateFormat();
- formater.applyPattern(“yyyy-MM-dd hh
ss”);
- try {
- date = formater.parse(dateStr);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return date;
- }
- public static Date toDate(String dateStr, String f) {
- Date date = null;
- SimpleDateFormat formater = new SimpleDateFormat();
- formater.applyPattern(f);
- try {
- date = formater.parse(dateStr);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- return date;
- }
- public static String toString(Date date) {
- String time;
- SimpleDateFormat formater = new SimpleDateFormat();
- formater.applyPattern(“yyyy-MM-dd hh
ss”);
- time = formater.format(date);
- return time;
- }
- public static String toString(Date date, String f) {
- String time;
- SimpleDateFormat formater = new SimpleDateFormat();
- formater.applyPattern(f);
- time = formater.format(date);
- return time;
- }
- public static void main(String[] args) {
- Date todayDate = new Date();//date类型
- System.out.println(todayDate);
- String t = DateUtil.toString(todayDate,”yyyy-MM-dd hh
ss”);//string类型
- System.out.println(t);
- todayDate = DateUtil.toDate(t, “yyyy-MM-dd hh
ss”);//date类型
- System.out.println(todayDate);
- }
- }
还没有评论,来说两句吧...