使用SimpleDateFormat格式化日期

来源:互联网 发布:素材下载站源码 编辑:程序博客网 时间:2024/05/29 21:32
import java.text.* ;import java.util.* ;public class DateDemo05{public static void main(String args[]) throws Exception{String strDate = "2008-10-19 10:11:30" ;// 准备第一个模板,从字符串中提取出日期数字String pat = "yyyy-MM-dd HH:mm:ss" ;SimpleDateFormat sdf = new SimpleDateFormat(pat) ;// 实例化模板对象Date d = sdf.parse(strDate) ;// 将给定的字符串中的日期提取出来System.out.println(d) ;// 输出Date对象System.out.println(sdf.format(d)) ;// 将日期变为新的格式}};

输出结果:

Sun Oct 19 10:11:30 CST 20082008-10-19 10:11:30

使用SimpleDateFormat格式化日期。 以上程序实现String向Date的操作转型

import java.text.* ;import java.util.* ; class DateTime{//声明日期格式化操作对象,直接对new Date()进行实例化private SimpleDateFormat simpleDateFormat=null;//得到完整日期,格式为:yyyy-MM-dd HH:mm:ss:SSSpublic String getDate() {this.simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");return this.simpleDateFormat.format(new Date());}//得到完整的日期,格式为:yyyy年MM月dd日HH时mm分ss秒SSS毫秒public String getDateComplete() {this.simpleDateFormat= new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒SSS毫秒");return this.simpleDateFormat.format(new Date());}//得到时间戳:yyyyMMddHHmmssSSSpublic String getTimeStamp() {this.simpleDateFormat= new SimpleDateFormat("yyyyMMddHHmmssSSS");return this.simpleDateFormat.format(new Date());}};public class Test{public static void main(String args[]){DateTime dTime=new DateTime();System.out.println("系统日期:"+dTime.getDate());System.out.println("中文日期:"+dTime.getDateComplete());System.out.println("时间戳:"+dTime.getTimeStamp());}}

输出结果

系统日期:2016-03-03 14:09:23:292
中文日期:2016年03月03日14时09分23秒293毫秒
时间戳:20160303140923293


0 0