java.util.Date与字符串格式化转换

作者 做棵大树 日期 2018-05-12
java.util.Date与字符串格式化转换

在页面上显示信息的时候,需要从数据库获取出生日期,此时该类型为日期类型,然后需要将该日期类型转为字符串显示在页面上,Java的API中为我们提供了日期与字符串相互转运的类DateForamtDateForamt是一个抽象类,所以平时使用的是它的子类SimpleDateFormat。SimpleDateFormat有4个构造函数,最经常用到是第二个。

1、日期与字符串String进行互转(格式化)

package zzu.xzy.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 df = new SimpleDateFormat(“yyyy-MM-dd”);
System.out.println(df.format(date));
df = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
System.out.println(df.format(date));
df = new SimpleDateFormat(“yyyy年MM月dd日 HH:mm:ss”);
System.out.println(df.format(date));
}
}

__________________________________________________
输出结果
1 2018-05-12
2 2018-05-12 13:40:06
3 2018年05月12日 13:40:06

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

package zzu.xzy.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

这样是可以进行解析的。