当前位置: 移动技术网 > IT编程>开发语言>Java > Java中Date与String相互转换的方法

Java中Date与String相互转换的方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

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

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

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

package com.test.dateformat;

import java.text.simpledateformat;
import java.util.date;

import org.junit.test;

public class date2string {
  @test
  public void test() {
    date date = new date();
    simpledateformat sdf = new simpledateformat("yyyy-mm-dd");
    system.out.println(sdf.format(date));
    sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    system.out.println(sdf.format(date));
    sdf = new simpledateformat("yyyy年mm月dd日 hh:mm:ss");
    system.out.println(sdf.format(date));
  }
}

2016-10-24
2016-10-24 21:59:06
2016年10月24日 21:59:06

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

package com.test.dateformat;

import java.text.parseexception;
import java.text.simpledateformat;

import org.junit.test;

public class string2date {
  @test
  public void test() throws parseexception {
    string string = "2016-10-24 21:59:06";
    simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    system.out.println(sdf.parse(string));
  }
}

mon oct 24 21:59:06 cst 2016

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

package com.test.dateformat;

import java.text.parseexception;
import java.text.simpledateformat;

import org.junit.test;

public class string2date {
  @test
  public void test() throws parseexception {
    string string = "2016-10-24";
    simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
    system.out.println(sdf.parse(string));
  }
}

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

package com.test.dateformat;

import java.text.parseexception;
import java.text.simpledateformat;

import org.junit.test;

public class string2date {
  @test
  public void test() throws parseexception {
    string string = "2016-10-24 21:59:06";
    simpledateformat sdf = new simpledateformat("yyyy-mm-dd");
    system.out.println(sdf.parse(string));
  }
}

mon oct 24 00:00:00 cst 2016

可以看出时分秒都是0,没有被解析,这是可以的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网