日期类型与字符串之间的转换,
1、日期类型 创建Date对象,表示当前时间 Date now=new Date(); 创建任意日期 DateFormat format=new SimpleDateFormat("yyyy-MM-dd");Date date=format.parse("1986-10-22");//将字符串类型转换成日期类型 2、字符串类型 日期类型可以直接输出,即 DateFormat format=new SimpleDateFormat("yyyy-MM-dd");
Date date=format.parse("1986-10-22");//将字符串类型转换成日期类型 System.out.println(date); 输出的结果如下: Wed Oct 22 00:00:00 CST 1986
如果想要输出的结果为:"1986-10-22",就必须把日期类型转换为字符串类型 DateFormat dformat=new SimpleDateFormat("yyyy-MM-dd");
Date date=dformat.parse("1986-10-22");//将字符串类型转换成日期类型 String out=dformat.format(date);//将日期类型转换成字符串类型 System.out.println(out); 输出的结果如下:
1986-10-22
注意: 1)字符串日期的格式可以随意设置,比如:yyyy-MM-dd;yyyy,MM,dd;yyyy年MM月dd日,都是可以的。 2)yyyy-MM-dd与yyyy-mm-dd是不一样的,其中MM代表月份,mm代表分钟。
下面再附上一段程序和结果,便于更好的理解: // 使用format()方法将日期转换为指定格式的文本
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm");
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 创建Date对象,表示当前时间
Date now=new Date();
// 调用format()方法,将日期转换为字符串并输出
System.out.println(sdf1.format(now));
System.out.println(sdf2.format(now));
System.out.println(sdf3.format(now));
// 使用parse()方法将文本转换为日期
String d = "2014-6-1 21:05:36";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 调用parse()方法,将字符串转换为日期
Date date1 =sdf.parse(d);
System.out.println(date1);
System.out.println(sdf.format(date1));
结果为: 2016年04月11日 16时36分20秒
2016/04/11 16:36
2016-04-11 16:36:20
Sun Jun 01 21:05:36 CST 2014
2014-06-01 21:05:36
本站文章为和通数据库网友分享或者投稿,欢迎任何形式的转载,但请务必注明出处.
同时文章内容如有侵犯了您的权益,请联系QQ:970679559,我们会在尽快处理。