Java日期格式化

日期转为指定格式字符串

package org.maoge.common;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo {
	public static void main(String[] args) {
		//默认输出格式
		Date date=new Date();
		System.out.println(date);//Fri Oct 27 16:56:37 CST 2017
		//日期格式化显示,首先定义格式
		SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMdd");//显示20171027格式
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");//显示2017-10-27格式
		SimpleDateFormat sdf3=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//显示2017-10-27 10:00:00格式
		SimpleDateFormat sdf4=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");//显示2017年10月27日10时00分00秒格式
		//将格式应用于日期
		System.out.println(sdf1.format(date));//20171027
		System.out.println(sdf2.format(date));//2017-10-27
		System.out.println(sdf3.format(date));//2017-10-27 17:11:13
		System.out.println(sdf4.format(date));//2017年10月27日17时11分13秒
	}
}

解析字符串为日期

package org.maoge.common;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo {
	public static void main(String[] args) {
		//首先定义格式
		SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//按格式进行转换
		String strDate1="20151010";//符合sdf1格式
		String strDate2="20171027 10:00:00";//不符合格式
		try {
			Date date1=sdf1.parse(strDate1);
			System.out.println(date1);//正常输出Sat Oct 10 00:00:00 CST 2015
			Date date2=sdf2.parse(strDate2);//报错java.text.ParseException: Unparseable date: "20171027 10:00:00"
			System.out.println(date2);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值