Java中Date与String的相互转换

分手后的思念是犯贱 2022-06-01 09:12 300阅读 0赞

我们在注册网站的时候,往往需要填写个人信息,如姓名,年龄,出生日期等,在页面上的出生日期的值传递到后台的时候是一个字符串,而我们存入数据库的时候确需要一个日期类型,反过来,在页面上显示的时候,需要从数据库获取出生日期,此时该类型为日期类型,然后需要将该日期类型转为字符串显示在页面上,Java的API中为我们提供了日期与字符串相互转运的类DateForamt。DateForamt是一个抽象类,所以平时使用的是它的子类SimpleDateFormat。SimpleDateFormat有4个构造函数,最经常用到是第二个。

1023471-20161024215423000-676416570.png

构造函数中pattern为时间模式,具体有什么模式,API中有说明,如下

1023471-20161024215601234-2054026259.png

1、日期转字符串(格式化)

  1. 1 package com.test.dateFormat;
  2. 2
  3. 3 import java.text.SimpleDateFormat;
  4. 4 import java.util.Date;
  5. 5
  6. 6 import org.junit.Test;
  7. 7
  8. 8 public class Date2String {
  9. 9 @Test
  10. 10 public void test() {
  11. 11 Date date = new Date();
  12. 12 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  13. 13 System.out.println(sdf.format(date));
  14. 14 sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  15. 15 System.out.println(sdf.format(date));
  16. 16 sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
  17. 17 System.out.println(sdf.format(date));
  18. 18 }
  19. 19 }
  20. 1 2016-10-24
  21. 2 2016-10-24 21:59:06
  22. 3 20161024 21:59:06

2、字符串转日期(解析)

  1. 1 package com.test.dateFormat;
  2. 2
  3. 3 import java.text.ParseException;
  4. 4 import java.text.SimpleDateFormat;
  5. 5
  6. 6 import org.junit.Test;
  7. 7
  8. 8 public class String2Date {
  9. 9 @Test
  10. 10 public void test() throws ParseException {
  11. 11 String string = "2016-10-24 21:59:06";
  12. 12 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  13. 13 System.out.println(sdf.parse(string));
  14. 14 }
  15. 15 }
  16. Mon Oct 24 21:59:06 CST 2016

在字符串转日期操作时,需要注意给定的模式必须和给定的字符串格式匹配,否则会抛出java.text.ParseException异常,例如下面这个就是错误的,字符串中并没有给出时分秒,那么SimpleDateFormat当然无法给你凭空解析出时分秒的值来

  1. 1 package com.test.dateFormat;
  2. 2
  3. 3 import java.text.ParseException;
  4. 4 import java.text.SimpleDateFormat;
  5. 5
  6. 6 import org.junit.Test;
  7. 7
  8. 8 public class String2Date {
  9. 9 @Test
  10. 10 public void test() throws ParseException {
  11. 11 String string = "2016-10-24";
  12. 12 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  13. 13 System.out.println(sdf.parse(string));
  14. 14 }
  15. 15 }

不过,给定的模式比字符串少则可以

  1. 1 package com.test.dateFormat;
  2. 2
  3. 3 import java.text.ParseException;
  4. 4 import java.text.SimpleDateFormat;
  5. 5
  6. 6 import org.junit.Test;
  7. 7
  8. 8 public class String2Date {
  9. 9 @Test
  10. 10 public void test() throws ParseException {
  11. 11 String string = "2016-10-24 21:59:06";
  12. 12 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  13. 13 System.out.println(sdf.parse(string));
  14. 14 }
  15. 15 }

发表评论

表情:
评论列表 (有 0 条评论,300人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JavaDateString相互转换

    我们在注册网站的时候,往往需要填写个人信息,如姓名,年龄,出生日期等,在页面上的出生日期的值传递到后台的时候是一个字符串,而我们存入数据库的时候确需要一个日期类型,反过来,在页