DateFormat的常用方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wpwbb510582246/article/details/83541347

构造方法:public SimpleDateFormat(String pattern),参数pattern是一个字符串,代表日期时间的自定义格式。常用的格式规则为:

标识字母(区分大小写) 含义
y
M
d
H
m
s

format方法:public String format(Date date),将Date对象格式化为字符串。

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
 把Date对象转换成String
*/
public class Demo03DateFormatMethod {
    public static void main(String[] args) {
Date date = new Date();
// 创建日期格式化对象,在获取格式化对象时可以指定风格
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
String str = df.format(date);
System.out.println(str); // 2008年1月23日
    }
}

parse方法:public Date parse(String source),将字符串解析为Date对象。

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
 把String转换成Date对象
*/
public class Demo04DateFormatMethod {
    public static void main(String[] args) throws ParseException {
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
String str = "2018年12月11日";
Date date = df.parse(str);
System.out.println(date); // Tue Dec 11 00:00:00 CST 2018
    }
}

猜你喜欢

转载自blog.csdn.net/wpwbb510582246/article/details/83541347