Android获取时间

常用类

date、Calendar

获取1970年之前的秒值会是负数。

例如

        toDate("0001年01月01日 08:00:00");
    public void toDate(String time) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            Date date = sdf.parse(time);
            LOG.d(TAG, "data.long = " + date.getTime());
            String str = sdf.format(new Date(0));
            LOG.d(TAG, "adata = " + str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

打印  data.long = -62135769600000
        adata = 1970年01月01日 08:00:00

new Date(0) 打印1970年1月1日 8点,是因为系统的时区是+8区。

    public void test2() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(1, 0, 1, 8, 0, 0);
        Date calendartodate = calendar.getTime();
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = sdf.format(calendartodate);
        LOG.d(TAG, "calendartodate = " + str);
        long sec1 = calendar.getTimeInMillis();
        LOG.d(TAG, "sec = " + sec1);
        calendar.set(1, 0, 1, 7, 0, 0);
        long sec2 = calendar.getTimeInMillis();
        LOG.d(TAG, "sec2 = " + sec2);
        if (sec1 > sec2) {
            LOG.d(TAG, "sec1-sec2 = " + (sec1 - sec2));
        } else {
            LOG.d(TAG, "sec2-sec1 = " + (sec2 - sec1));
        }

    }
//打印
/*
calendartodate = 0001-01-01 08:00:00
 sec = -62135769599045
 sec2 = -62135773199045
 sec1-sec2 = 3600000*/
发布了21 篇原创文章 · 获赞 5 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/linchuanzhi_886/article/details/89715014
今日推荐