DateFormat和SimpleDateFormat

DateFormat和SimpleDateFormat

DateFormat类的作用

把时间对象转化成指定格式的字符串。反之,把指定格式的字符串转化成时间对象。

DateFormat是一个抽象类 , 一般使用它的的子类SimpleDateFormat类来实现。

DateFormat类和SimpleDateFormat类的使用:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class _08DateFromatDemo {

	public static void main(String[] args) throws ParseException {
		// TODO Auto-generated method stub
	      // new出 SimpleDateFormat对象
	      SimpleDateFormat s1 =new SimpleDateFormat("yyy-MM-dd hh:mm:ss"); //"yyy年MM月dd日 hh时mm分ss秒"
	     // SimpleDateFormat s3 =new SimpleDateFormat("yyy年MM月dd日 hh:mm:ss");
	      SimpleDateFormat s2 = new SimpleDateFormat("yyyy-M-dd");
	     // System.out.println(s3);
	      
	      // 将时间对象按照“格式字符串指定的格式”转换为相应的字符串
	      String daytime = s1.format(new Date());   // format方法用于将对象格式化为指定模式的字符串
	      System.out.println(daytime);
	      System. out . println(s2.format(new Date()));
	      System. out .println(new SimpleDateFormat("hh:mm:ss").format(new Date()));
	      // 将符合指定格式的字符串转成成时间对像.字符串格式健要和指定格式一致。
	      String time= "2007-18-7";
	      Date date =s2.parse(time) ;
	      System.out .println("date1:"+date) ;
	      time ="2007-10-7 20:15:30";
	      date =s1.parse(time);
	      System.out.println("date2:"+ date);
	}
}

 

 

实例:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class _08DateFromatDemo {

	public static void main(String[] args) throws ParseException {
		// TODO Auto-generated method stub
	//把时间对象按照“格式字符串指定的格式”转成相应的字符串
		DateFormat  df  = new SimpleDateFormat("yyyy-MM-dd  hh:mm:ss");
		String str  =  df.format(new Date(4000000)); 
		System.out.println(str);
			
		//把字符串按照“格式字符串指定的格式”转成相应的时间对象
		DateFormat  df2 = new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒");
		
		Date  date = df2.parse("1983年5月10日 10时45分59秒");
		System.out.println(date);
			
		//测试其他的格式字符。比如:利用D,获得本时间对象是所处年份的第几天。
		DateFormat  df3  = new SimpleDateFormat("D");
		String str3  =  df3.format(new Date()); 
		System.out.println(str3);
}
}

在使用时要注意格式不匹配的问题,格式一定要相匹配。

 

 

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值