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;
    }

整理出 45 本电子版书籍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

网罗开发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值