现在的位置: 首页 > 综合 > 正文

java中时间类代码解析

2013年06月27日 ⁄ 综合 ⁄ 共 1407字 ⁄ 字号 评论关闭
 
import java.text.*; 
import java.util.*; 
/* 
* 时间类的练习 
*/ 
public class DateTest 
{ 

/** 
    * 将某个日期以固定(自定义)格式转化成字符串 
    * @param date 
    * @return String 
    */ 
    public String dateToStr(Date date) 
    {   
     //以下各种格式都可以,只要保证各个字符串格式正确,中间用什么分隔符无所谓,
     //但注意表示年必须用yyyy,其它字符串字段,大小写都行 

     //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:ms"); 
    //SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd hh mm ss ms");  //常用 
    //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-ms");  //常用 
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日hh时mm分ss秒ms分");//经典 
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-Ms"); 
       String str = sdf.format(date); 
       return str; 
    } 

    /* 
    * 将某个日期以本地OS的local方式输出 
    */ 

    public String dateToStr1(Date date)
    { 
        String myString=DateFormat.getDateInstance().format(date); 
        return myString; 
    } 

    public static void main(String[] args) 
    { 
        //第一种时间格式,输出格式为星期,月份,日期,小时,分钟,秒,时区,年 
        System.out.println(new Date().toString()); 
        // 第二种格式 
        String myString=new DateTest().dateToStr1(new Date()); 
        System.out.println("当前时间为(用本地OS输出):"+myString); 
        
        //第三种格式为 
        String str=new DateTest().dateToStr(new Date()); 
        System.out.println("当前时间为(用指定格式):"+str); 
        
        //第四种格式为,指定格式,指定日期(例如奥运会开幕时间) 
        Date opendt=null; 
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-ms"); 
        try { 
        opendt=sdf.parse("2008-08-08-18-00-00-00"); 
        } catch (ParseException e) { 
        e.printStackTrace(); 
        } 
        System.out.println("开幕式:"+opendt.toString()); 
        
        //Calendar类 
        Calendar calendar=Calendar.getInstance(); 
        System.out.println("今天是星期:"+calendar.get(Calendar.DAY_OF_WEEK)); 
    } 

}

抱歉!评论已关闭.