Java 日期类介绍与使用(Date,Calendar等)

1.UTC & GTM

GMT就是格林尼治标准时间,它是Greenwich mean time的简称。

UTC则是协调世界时间,它是coordinated universal time的时间。它是一种更精确的GMT。

2. java.util.Date类

Date类的时间实质是通过计算出来的,其实它叫做DateTime更合适,它的时间已经能精确表示到秒。它的构造方法
     /**
     * Allocates a <code>Date</code> object and initializes it so that 
     * it represents the time at which it was allocated, measured to the 
     * nearest millisecond. 
     *
     * @see     java.lang.System#currentTimeMillis()
     */
    public Date() {
        this(System.currentTimeMillis());
    }

    /**
     * Allocates a <code>Date</code> object and initializes it to 
     * represent the specified number of milliseconds since the 
     * standard base time known as "the epoch", namely January 1, 
     * 1970, 00:00:00 GMT. 
     *
     * @param   date   the milliseconds since January 1, 1970, 00:00:00 GMT.
     * @see     java.lang.System#currentTimeMillis()
     */
    public Date(long date) {
        fastTime = date;
    }
它是在一个时间的基准上,然后把传入的参数精确到毫秒,计算得到现在的时间。
目前不建议使用Date中的getDate、getYea等方法。以Calendar类来替代。

3. java.util.Calendar类

calendar直译为日历,它做为Date类的补充,下面以一段代码来说明下calendar的应用。

<span style="white-space:pre">	</span>Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);//获取年份
        int month = cal.get(Calendar.MONTH);//获取月份
        int day = cal.get(Calendar.DATE);//获取日
        int hour = cal.get(Calendar.HOUR);//小时
        int minute = cal.get(Calendar.MINUTE);//分           
        int second = cal.get(Calendar.SECOND);//秒
        Date time = cal.getTime(); // 获取当前时间


4. Calendar与Date相互转换

1)Calendar转换为Date
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();

2)Date转换为Calendar

Calendar cal = Calendar.getInstance();
Date date = new Date();
cal.setTime(date);










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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值