Java中Date与String的相互转换

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

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

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

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));
    }
}

 

 

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

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));
    }
}

 

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

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));
    }
}

 

 

能够看出时分秒都是0,没有被解析,这是能够的。网站

 

【当你用心写完每一篇博客以后,你会发现它比你用代码实现功能更有成就感!】
相关文章
相关标签/搜索