首页 > 代码库 > Java中Date对象与String互转

Java中Date对象与String互转

 1 package com.java.test;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 public class DateStringTransfrom {
 8 
 9     public static void main(String[] args) {
10         stringTransfromDateOne();
11         //stringTransformDateTwo();
12         //DateTransformStringOne();
13         //DateTransformStringTwo();
14     }
15 
16     // yyyy-MM-dd HH:mm:ss格式的字符串转换为Date对象
17     static void stringTransfromDateOne() {
18         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
19         Date date = null;
20         try {
21             date = dateFormat.parse("2010-10-01 12:00:00");
22         } catch (ParseException e) {
23             // TODO Auto-generated catch block
24             e.printStackTrace();
25         }
26         System.out.println("date object: " + date);
27     }
28 
29     // yyyy-MM-dd格式的字符串转换为Date对象
30     static void stringTransformDateTwo() {
31         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
32         Date date = null;
33         try {
34             date = dateFormat.parse("2010-10-01");
35         } catch (ParseException e) {
36             // TODO Auto-generated catch block
37             e.printStackTrace();
38         }
39         System.out.println("date object: " + date);
40     }
41 
42     // 当前时间对象转换为字符串
43     static void DateTransformStringOne() {
44         Date date = new Date();
45         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
46         String dateString = dateFormat.format(date);
47         System.out.println("dateString: " + dateString);
48     }
49     
50     //指定日期对象转换为字符串
51     static void DateTransformStringTwo() {
52         // 创建指定日期对象
53         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
54         Date date = null;
55         try {
56             date = dateFormat.parse("2010-10-01 12:00:00");
57         } catch (ParseException e) {
58             // TODO Auto-generated catch block
59             e.printStackTrace();
60         }
61 
62         String dateString = dateFormat.format(date);
63         System.out.println("dateString: " + dateString);
64 
65     }
66 
67 }

 

Java中Date对象与String互转