1.1 String -> Date
- String dateStr = "2010/05/04 12:34:23";
- Date date = new Date();
- //注意format的格式要与日期String的格式相匹配
- DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- try {
- date = sdf.parse(dateStr);
- System.out.println(date.toString());
- } catch (Exception e) {
- e.printStackTrace();
- }
String dateStr = "2010/05/04 12:34:23"; Date date = new Date(); //注意format的格式要与日期String的格式相匹配 DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); try { date = sdf.parse(dateStr); System.out.println(date.toString()); } catch (Exception e) { e.printStackTrace(); }
1.2 Date -> String
日期向字符串转换,可以设置任意的转换格式format
- String dateStr = "";
- Date date = new Date();
- //format的格式可以任意
- DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
- DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH/mm/ss");
- try {
- dateStr = sdf.format(date);
- System.out.println(dateStr);
- dateStr = sdf2.format(date);
- System.out.println(dateStr);
- } catch (Exception e) {
- e.printStackTrace();
- }
String dateStr = ""; Date date = new Date(); //format的格式可以任意 DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH/mm/ss"); try { dateStr = sdf.format(date); System.out.println(dateStr); dateStr = sdf2.format(date); System.out.println(dateStr); } catch (Exception e) { e.printStackTrace(); }
3.1 Timestamp -> Date
- Timestamp ts = new Timestamp(System.currentTimeMillis());
- Date date = new Date();
- try {
- date = ts;
- System.out.println(date);
- } catch (Exception e) {
- e.printStackTrace();
- }
Timestamp ts = new Timestamp(System.currentTimeMillis()); Date date = new Date(); try { date = ts; System.out.println(date); } catch (Exception e) { e.printStackTrace(); }