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

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

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;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容