在页面上显示信息的时候,需要从数据库获取出生日期,此时该类型为日期类型,然后需要将该日期类型转为字符串显示在页面上,Java 的 API 中为我们提供了日期与字符串相互转运的类DateForamt。DateForamt是一个抽象类,所以平时使用的是它的子类 SimpleDateFormat。SimpleDateFormat 有 4 个构造函数,最经常用到是第二个。
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
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
这样是可以进行解析的。
© 2018 www.qingketang.net 鄂ICP备18027844号-1
武汉快勤科技有限公司 13554402156 武汉市东湖新技术开发区关山二路特一号国际企业中心6幢4层7号
扫码关注,全站教程免费播放
订单金额:
支付金额:
支付方式: