date日期类型与String类型的相互转化
来源:互联网 发布:淘宝延长收款怎么取消 编辑:程序博客网 时间:2024/05/21 22:37
- 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:m: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:m: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();
- System.out.println(todayDate);
- String t = DateUtil.toString(todayDate,"yyyy-MM-dd hh:m:ss");
- System.out.println(t);
- todayDate = DateUtil.toDate(t, "yyyy-MM-dd hh:m:ss");
- System.out.println(todayDate);
- }
-
- }