android 获取时间戳

由于项目需要使用时间戳Timestamp:

1.什么是时间戳

时间戳的定义:通常是一个字符序列,唯一地标识某一刻的时间。数字时间戳技术是数字签名技术一种变种的应用。

规则:是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数(引用自百度百科)

一般数据库里如果用Date这个类的话,那你取出来的时候只能到某一天,也就是日,但是Timestamp的话,就是到小时一直到纳秒,很精确的。

2.时间戳的好处

时间戳就是一种类型,只是精度很高,比datetime要精确的多,通常用来防止数据出现脏读现象。

3.时间戳和时间的互相转换
/* 
     * 将时间转换为时间戳
     */    
    public static String dateToStamp(String s) throws ParseException{
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    /* 
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

4..在Java中如何获取时间戳
  • Date类提供了getTime方法:Date().getTime()可以获取时间戳
  • Calendar.getInstance().getTimeInMillis();
  • System.currentTimeMillis(),效率更佳。

在不同的开发语言中,获取到的时间戳的长度是不同的,例如C++中的时间戳是精确到秒的,但是Java中的时间戳是精确到毫秒的,这样在涉及到不同语言的开发过程中,如果不进行统一则会出现一些时间不准确的问题。

5.Java中的两种获取精确到秒的时间戳的方法:

Java中的时间戳的毫秒主要通过最后的三位来进行计量的,我们通过两种不同的方式将最后三位去掉。


方法一:通过String.substring()方法将最后的三位去掉
 /**
     * 获取精确到秒的时间戳
     * @return
     */
    public static int getSecondTimestamp(Date date){
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Integer.valueOf(timestamp.substring(0,length-3));
        } else {
            return 0;
        }
    }

方法二:通过整除将最后的三位去掉

/**
     * 获取精确到秒的时间戳
     * @param date
     * @return
     */
    public static int getSecondTimestampTwo(Date date){
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime()/1000);
        return Integer.valueOf(timestamp);
    }
    原文作者:Lost_Robot
    原文地址: https://www.jianshu.com/p/43dbc2e01376
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞