Android 获取当前时间及时间戳的互换

来源:互联网 发布:死亡诗社知乎 编辑:程序博客网 时间:2024/06/14 18:29

在项目开发中,难免会遇到使用当前时间,比如实现网络请求上传报文、预约、日历等功能。

1. 获取年月日时分秒

在获取时间之前,首先要引入SimpleDateFormat:

import java.text.SimpleDateFormat;

实现代码:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");Date curDate = new Date(System.currentTimeMillis());//获取当前时间       String str  = formatter.format(curDate);

str就是我们需要的时间,代码中(“yyyy年MM月dd日 HH:mm:ss”)这个时间的样式是可以根据我们的需求进行修改的,比如:
20170901112253 ==> (“yyyyMMddHHmmss”)

如果只想获取年月,代码如下:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");Date curDate = new Date(System.currentTimeMillis());//获取当前时间       String str  = formatter.format(curDate);

2. 区分系统时间是24小时制还是12小时制

在获取之前,首先要引入ContentResolver:

import android.content.ContentResolver;

代码如下:

ContentResolver cv = this.getContentResolver();String strTimeFormat = android.provider.Settings.System.getString(cv,                android.provider.Settings.System.TIME_12_24);if(strTimeFormat.equals("24")){   Log.i("activity","24");}

3. 字符串转时间戳

代码如下:

    //字符串转时间戳    public static String getTime(String timeString){        String timeStamp = null;        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");        Date d;        try{            d = sdf.parse(timeString);            long l = d.getTime();            timeStamp = String.valueOf(l);        } catch(ParseException e){            e.printStackTrace();        }        return timeStamp;    }

4. 时间戳转字符串

代码如下:

    //时间戳转字符串    public static String getStrTime(String timeStamp){        String timeString = null;        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");        long  l = Long.valueOf(timeStamp);        timeString = sdf.format(new Date(l));//单位秒        return timeString;    }