获取系统时间以及时间戳的理解与使用

版权声明:版权声明@忆痕惜dxh | https://blog.csdn.net/qq_38717971/article/details/83111678

所谓等待,不过只是个念想,藏在心里见不得阳光,像个吸血鬼一样,醒来咬你一口,让你死去活来的疼。


近日在做开发的时候,用到DatePicker控件,需要在后台用代码设置minDate和maxDate的值,然后发现需要传入的参数是一个Long型以毫秒为单位的时间戳格式,自此第一次了解到了时间戳的概念,还是非常好用的。

时间戳(timestamp),是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。通俗的讲, 时间戳是一份能够表示一份数据在一个特定时间点已经存在的完整的可验证的数据。 它的提出主要是为用户提供一份电子证据, 以证明用户的某些数据的产生时间。 在实际应用上, 它可以使用在包括电子商务、 金融活动的各个方面, 尤其可以用来支撑公开密钥基础设施的 “不可否认” 服务。

1、获取系统时间

方法一

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//获取当前时间
Date date = new Date(System.currentTimeMillis());
方法二

Calendar calendar = Calendar.getInstance();
//获取系统的日期
//年
int year = calendar.get(Calendar.YEAR);
//月
int month = calendar.get(Calendar.MONTH)+1;
//日
int day = calendar.get(Calendar.DAY_OF_MONTH);
//获取系统时间
//小时
int hour = calendar.get(Calendar.HOUR_OF_DAY);
//分钟
int minute = calendar.get(Calendar.MINUTE);
//秒
int second = calendar.get(Calendar.SECOND);
方法三

Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料。
t.setToNow(); // 取得系统时间。
int year = t.year;
int month = t.month+1;
int day = t.monthDay;
int hour = t.hour; // 0-23
int minute = t.minute;
int second = t.second;

 2、获取系统时间戳

public long getCurTimeLong(){
    long time=System.currentTimeMillis();
    return time;
}

 3、时间戳转换为字符串

public static String getDateToString(long milSecond, String pattern) {
    Date date = new Date(milSecond);
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    return format.format(date);
}

4、字符串转换为时间戳

public static long getStringToDate(String dateString, String pattern) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
    Date date = new Date();
    try{
        date = dateFormat.parse(dateString);
    } catch(ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return date.getTime();
}

猜你喜欢

转载自blog.csdn.net/qq_38717971/article/details/83111678