java之SimpleDateFormat日期格式化

SimpleDateFormat

是一个以与语言环境有关的方式来格式化和解析日期的具体类。它允许进行格式化(日期 -> 文本)、解析(文本 -> 日期)和规范化。


构造方法

SimpleDateFormat()
          用默认的模式和默认语言环境的日期格式符号构造 SimpleDateFormat
SimpleDateFormat(String pattern)
          用给定的模式和默认语言环境的日期格式符号构造 SimpleDateFormat

日期格式化方法(Date转String)

1.通过构造方法设置日期格式


public class SimpleDateFormatDemo {
	public static void main(String[] args) {
		//创建一个日期对象获取当前时间
		Date date = new Date();
		//通过构造方法来设置格式化日期的格式信息
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//调用format方法对日期进行格式化
		String format = simpleDateFormat.format(date);
		System.out.println(format);
	}

}

打印结果:

2019-07-24 19:58:55

2.通过applyPattern方法设置格式

public class SimpleDateFormatDemo2 {
	public static void main(String[] args) {
		//创建一个日期对象获取当前时间
		Date date = new Date();
		//获得simpleDateFormat对象
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
		//通过applyPattern来设置日期格式
		simpleDateFormat.applyPattern("yyyy-MM-dd HH:mm:ss");
		//调用format方法对日期进行格式化
		String format = simpleDateFormat.format(date);
		System.out.println(format);
	}

}

打印结果:

2019-07-24 19:59:46

日期解析方法(String转Date)

Date parse(String source) 将符合格式的指定字符串转换为Date

public class SimpleDateFormatDemo3 {
	public static void main(String[] args) throws ParseException {
		//测试的字符串数据
		String str1="2019-07-24 19:37:54";
		String str2="2019年07月24日 19:37:54";
		String str3="2019/07/24 19:37:54";
		//给定格式的simpleDateFormat对象
		SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		//通过parse方法解析字符串日期
		Date date1 = simpleDateFormat1.parse(str1);
		Date date2 = simpleDateFormat2.parse(str2);
		Date date3 = simpleDateFormat3.parse(str3);
		//打印Date数据
		System.out.println(date1);
		System.out.println(date2);
		System.out.println(date3);
	}
}

打印结果:

Wed Jul 24 19:37:54 CST 2019
Wed Jul 24 19:37:54 CST 2019
Wed Jul 24 19:37:54 CST 2019

ps:parse()中引入的日期参数,格式必须与调用该方法的SimpleDateFormat对象封装的格式一致,若不一致会报错

Parse格式写法:

字母日期或时间元素表示示例
GEra 标志符TextAD
yYear1996; 96
M年中的月份MonthJuly; Jul; 07
w年中的周数Number27
W月份中的周数Number2
D年中的天数Number189
d月份中的天数Number10
F月份中的星期Number2
E星期中的天数TextTuesday; Tue
aAm/pm 标记TextPM
H一天中的小时数(0-23)Number0
k一天中的小时数(1-24)Number24
Kam/pm 中的小时数(0-11)Number0
ham/pm 中的小时数(1-12)Number12
m小时中的分钟数Number30
s分钟中的秒数Number55
S毫秒数Number978
z时区General time zonePacific Standard Time; PST; GMT-08:00
Z时区RFC 822 time zone-0800
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值