zoukankan      html  css  js  c++  java
  • Java中的日期与时间

    日期与时间

    最常用的几个类,Date、DateFormat、Calendar、Locale

    Date

    1.无参构造方法

    //根据当前系统默认的毫秒值创建时间对象
        public Date() {
            this(System.currentTimeMillis());
        }
    

    2.根据毫秒值创建时间对象

       long time = 1000*60*60;
       Date d = new Date(time);
    

    3.传入年月日时分秒创建时间对象

    Date d2 =  new Date(20,10,10,11,11,11)
    //这得到的时间并不是20-10-10这种
    //下面是源码
    public Date(int year, int month, int date, int hrs, int min, int sec) {
         int y = year + 1900;
         // month is 0-based. So we have to normalize month to support Long.MAX_VALUE.
         if (month >= 12) {
             y += month / 12;
             month %= 12;
         } else if (month < 0) {
             y += CalendarUtils.floorDivide(month, 12);
             month = CalendarUtils.mod(month, 12);
         }
         BaseCalendar cal = getCalendarSystem(y);
         cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());
         cdate.setNormalizedDate(y, month + 1, date).setTimeOfDay(hrs, min, sec, 0);
         getTimeImpl();
         cdate = null;
     }
    

    DateFormat

    DateFormat是日期时间格式化子类的抽象类,它以与语言无关的方式格式化并解析日期和时间。
    他是抽象类,使用其子类SimpleDateFormat

    DateFormat 类本身的内部提供了可以直接为其实例化的操作

    //得到日期的DateFormat对象:
    public static final DateFormat getDateInstance();
    
    //得到日期时间的DateFormat对象:
    public static final DateFormat getDateTimeInstance();
    
    //使用DateFormat类格式化Date类日期
    public final String format(Date date)
    

    SimpleDateFormat类
    SimpleDateFormat函数的继承关系:
    java.lang.Object
    |
    +—-java.text.Format
       |
       +—-java.text.DateFormat
          |
          +—-java.text.SimpleDateFormat

    //构造方法:
    public SimpleDateFormat(String pattern)
    
    //转换:
    public Date parse(String source)throws ParseException //-->此时取得的是全部时间数。
    
    //格式化:
    public final String Format(Date date)   //-->将时间重新格式化成字符串显示。
    

    把Date转化成指定的日期格式

    public class FormatDateTime {
         public static void main(String[] args) {
             SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
             SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd HH:mm"); 
             SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//等价于now.toLocaleString()
             SimpleDateFormat myFmt3=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E ");
             SimpleDateFormat myFmt4=new SimpleDateFormat("一年中的第 D 天 一年中第w个星期 一月中第W个星期 在一天中k时 z时区");
             Date now=new Date();
             System.out.println(myFmt.format(now));
             System.out.println(myFmt1.format(now));
             System.out.println(myFmt2.format(now));
             System.out.println(myFmt3.format(now));
             System.out.println(myFmt4.format(now));
             System.out.println(now.toGMTString());
             System.out.println(now.toLocaleString());
             System.out.println(now.toString());
         }    
    }
    

    把给定的字符串中的日期提取为Date

    这样做,通常是一个日期字符串,但不是想要的格式,可以先转化为Date,再转化为其它格式。

    import java.text.* ;  
    import java.util.* ;  
    public class DateDemo05{  
        public static void main(String args[]){  
            String strDate = "2008-10-19 10:11:30.345" ;  
            // 准备第一个模板,从字符串中提取出日期数字  
            String pat1 = "yyyy-MM-dd HH:mm:ss.SSS" ;  
            // 准备第二个模板,将提取后的日期数字变为指定的格式  
            String pat2 = "yyyy年MM月dd日 HH时mm分ss秒SSS毫秒" ;  
            SimpleDateFormat sdf1 = new SimpleDateFormat(pat1) ;        // 实例化模板对象  
            SimpleDateFormat sdf2 = new SimpleDateFormat(pat2) ;        // 实例化模板对象  
            Date d = null ;  
            try{  
                d = sdf1.parse(strDate) ;   // 将给定的字符串中的日期提取出来  
            }catch(Exception e){            // 如果提供的字符串格式有错误,则进行异常处理  
                e.printStackTrace() ;       // 打印异常信息  
            }  
            System.out.println(sdf2.format(d)) ;    // 将日期变为新的格式  
        }  
    };
    

    DateFormat 和SimpleDateFormat 的区别

    1.DateFormat 可以直接使用,但其本身是一个抽象类,可以根据Locate指定的区域得到对应的日期时间格式

    2.SimpleDateFormat 类是DateFormat 类的子类,一般情况下来讲 DateFormat 类很少会直接使用。而都使用SimpleDateFormat 类完成。

    1、DateFormat:是抽象类,所以使用子类SimpleDateFormat
     
    2、SimpleDateFormat类构造方法:
        public SimpleDateFormat():使用默认模式。
        public SimpleDateFormat(String pattern):使用给定的模式。
            API规定的模式:y M d H m s
      
    3、SimpleDateFormat类成员方法:
        public final String format(Date date):日期格式化为日期字符串。
        pattern Date parse(String source):日期字符串解析为日期。
    

    Calendar

    Calendar:它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等日历字段之间的转换提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。

    一、构造方法
    protected Calendar() :由于修饰符是protected,所以无法直接创建该对象。需要通过别的途径生成该对象。

    二、成员方法
    Calendar类的成员方法
    static Calendar getInstance()

    使用默认时区和区域设置获取日历。通过该方法生成Calendar对象。如下所示:

    Calendar cr=Calendar.getInstance();
    public void set(int year,int month,int date,int hourofday,int minute,int second)	设置日历的年、月、日、时、分、秒。
    public int get(int field)	返回给定日历字段的值。所谓字段就是年、月、日等等。
    public void setTime(Date date)	使用给定的Date设置此日历的时间。Date------Calendar
    public Date getTime()	返回一个Date表示此日历的时间。Calendar-----Date
    abstract void add(int field,int amount)	按照日历的规则,给指定字段添加或减少时间量。
    public long getTimeInMillies()	以毫秒为单位返回该日历的时间值。
    

    三、日历字段
    日历字段包含以下两种:一种是表示时间的单位,例如年、月、日等等。另一种是具体的日期,例如一月、二月、三月、一日、二日、三日、一点钟、两点钟等等具体的时间。前一种一般时获取的时候使用,后一种一般判断的时候使用。

    时间单位字段:

    YEAR 年 MINUTE 分
    DAY_OF_WEEK_IN_MONTH

    某月中第几周
    MONTH 月 SECOND/MILLISECOND 秒/毫秒 WEEK_OF_MONTH 日历式的第几周
    DATE 日 DAY_OF_MONTH
    和DATE一样

    DAY_OF_YEAR 一年的第多少天
    HOUR_OF_DAY 时 DAY_OF_WEEK 周几 WEEK_OF_YEAR 一年的第多少周

    AM_PM 返回1则表示是下午,返回0表示上午。

    public class CalendarDemo {
    	public static void main(String[] args) {
    		// 其日历字段已由当前日期和时间初始化:
    		Calendar rightNow = Calendar.getInstance(); // 子类对象
    		// 获取年
    		int year = rightNow.get(Calendar.YEAR);
    		// 获取月
    		int month = rightNow.get(Calendar.MONTH);
    		// 获取日
    		int date = rightNow.get(Calendar.DATE);
    		//获取几点
    		int hour=rightNow.get(Calendar.HOUR_OF_DAY);
    		//获取上午下午
    		int moa=rightNow.get(Calendar.AM_PM);
    		if(moa==1)
    			System.out.println("下午");
    		else
    			System.out.println("上午");
     
    		System.out.println(year + "年" + (month + 1) + "月" + date + "日"+hour+"时");
    		rightNow.add(Calendar.YEAR,5);
    		rightNow.add(Calendar.DATE, -10);
    		int year1 = rightNow.get(Calendar.YEAR);
    		int date1 = rightNow.get(Calendar.DATE);
    		System.out.println(year1 + "年" + (month + 1) + "月" + date1 + "日"+hour+"时");
    	}
    }
    

    注意:month是从0开始的,而月份是从1开始的,所以month需要加一

    Locale

    Locale一般用于国际化,Locale表示一个特定的地区,Locale类支持非常多的国家和地区。我们可以通过以下方法,查看Locale支持的全部区域:

    Locale[] ls = Locale.getAvailableLocales();
    for (Locale locale:ls) {
      System.out.println("locale :"+locale);
    }
    

    主要构造函数

    // Locale的构造函数
    Locale(String language)
    Locale(String language, String country)
    Locale(String language, String country, String variant)
    

    使用例子:
    在这里插入图片描述
    有关java国际化,另外一篇文章有描述。

  • 相关阅读:
    xml基础一
    FileStream
    串口、COM口、RS232、RS485、USB区别
    DotNet知识点五
    DotNet知识点四
    DotNet知识点三
    DotNet知识点二
    day02 关键字、添加注释、标识符、常量、变量、变量的定义、变量定义注意事项、转义字符
    day01
    22_Map集合(重点)
  • 原文地址:https://www.cnblogs.com/scholar-hwg/p/12060308.html
Copyright © 2011-2022 走看看