Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Android获取当前时间

Android实现获取当前时间并转为时间戳

作者:网罗开发

在项目开发中,难免会遇到使用当前时间,比如实现网络请求上传报文、预约、日历等功能,本文将为大家详细介绍如何使用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;
    }

方法补充

1.Android中获取当前时间戳

Android获取时间戳的四种方法如下:

long timecurrentTimeMillis = System.currentTimeMillis();
long timeGetTime =new Date().getTime();
long timeSeconds = System.currentTimeMillis();
long timeMillis = Calendar.getInstance().getTimeInMillis();

Log.d(TAG, "  当前时间戳1--->:"+timecurrentTimeMillis);
Log.d(TAG, "  当前时间戳2--->:"+timeGetTime);
Log.d(TAG, "  当前时间戳3--->:"+timeSeconds);
Log.d(TAG, "  当前时间戳4--->:"+timeMillis);

2.Android实现 时间戳与日期间的各种互换的时间工具类

完整代码如下:

package com.pts.peoplehui.utils;  
  
import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.util.Date;  
import java.util.Locale;  
  
public class DateUtils {  
  
    public static String getTodayDateTime() {  
        SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”,  
                Locale.getDefault());  
        return format.format(new Date());  
    }  
  
    /** 
     * 掉此方法输入所要转换的时间输入例如(”2014年06月14日16时09分00秒”)返回时间戳 
     *  
     * @param time 
     * @return 
     */  
    public String data(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy年MM月dd日HH时mm分ss秒”,  
                Locale.CHINA);  
        Date date;  
        String times = null;  
        try {  
            date = sdr.parse(time);  
            long l = date.getTime();  
            String stf = String.valueOf(l);  
            times = stf.substring(0, 10);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return times;  
    }  
  
    public static String getTodayDateTimes() {  
        SimpleDateFormat format = new SimpleDateFormat(“MM月dd日”,  
                Locale.getDefault());  
        return format.format(new Date());  
    }  
      
    /** 
     * 获取当前时间 
     *  
     * @return 
     */  
    public static String getCurrentTime_Today() {  
        SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd-HH-mm-ss”);  
        return sdf.format(new java.util.Date());  
    }  
  
    /** 
     * 调此方法输入所要转换的时间输入例如(”2014-06-14-16-09-00”)返回时间戳 
     *  
     * @param time 
     * @return 
     */  
    public static String dataOne(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy-MM-dd-HH-mm-ss”,  
                Locale.CHINA);  
        Date date;  
        String times = null;  
        try {  
            date = sdr.parse(time);  
            long l = date.getTime();  
            String stf = String.valueOf(l);  
            times = stf.substring(0, 10);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return times;  
    }  
  
    public static String getTimestamp(String time, String type) {  
        SimpleDateFormat sdr = new SimpleDateFormat(type, Locale.CHINA);  
        Date date;  
        String times = null;  
        try {  
            date = sdr.parse(time);  
            long l = date.getTime();  
            String stf = String.valueOf(l);  
            times = stf.substring(0, 10);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return times;  
    }  
  
    /** 
     * 调用此方法输入所要转换的时间戳输入例如(1402733340)输出(”2014年06月14日16时09分00秒”) 
     *  
     * @param time 
     * @return 
     */  
    public static String times(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy年MM月dd日HH时mm分ss秒”);  
        @SuppressWarnings(“unused”)  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        return times;  
  
    }  
      
    /** 
     * 调用此方法输入所要转换的时间戳输入例如(1402733340)输出(”2014-06-14  16:09:00”) 
     *  
     * @param time 
     * @return 
     */  
    public static String timedate(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);  
        @SuppressWarnings(“unused”)  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        return times;  
  
    }  
  
    /** 
     * 调用此方法输入所要转换的时间戳输入例如(1402733340)输出(”2014年06月14日16:09”) 
     *  
     * @param time 
     * @return 
     */  
    public static String timet(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy年MM月dd日  HH:mm”);  
        @SuppressWarnings(“unused”)  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        return times;  
  
    }  
  
    /** 
     * @param time斜杠分开 
     * @return 
     */  
    public static String timeslash(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy/MM/dd,HH:mm”);  
        @SuppressWarnings(“unused”)  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        return times;  
  
    }  
  
    /** 
     * @param time斜杠分开 
     * @return 
     */  
    public static String timeslashData(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy/MM/dd”);  
        @SuppressWarnings(“unused”)  
        long lcc = Long.valueOf(time);  
//      int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(lcc * 1000L));  
        return times;  
  
    }  
      
    /** 
     * @param time斜杠分开 
     * @return 
     */  
    public static String timeMinute(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“HH:mm”);  
        @SuppressWarnings(“unused”)  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        return times;  
  
    }  
  
    public static String tim(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyyMMdd HH:mm”);  
        @SuppressWarnings(“unused”)  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        return times;  
    }  
  
    public static String time(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy-MM-dd HH:mm”);  
        @SuppressWarnings(“unused”)  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        return times;  
    }  
  
    // 调用此方法输入所要转换的时间戳例如(1402733340)输出(”2014年06月14日16时09分00秒”)  
    public static String times(long timeStamp) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“MM月dd日  #  HH:mm”);  
        return sdr.format(new Date(timeStamp)).replaceAll(“#”,  
                getWeek(timeStamp));  
  
    }  
  
    private static String getWeek(long timeStamp) {  
        int mydate = 0;  
        String week = null;  
        Calendar cd = Calendar.getInstance();  
        cd.setTime(new Date(timeStamp));  
        mydate = cd.get(Calendar.DAY_OF_WEEK);  
        // 获取指定日期转换成星期几  
        if (mydate == 1) {  
            week = ”周日”;  
        } else if (mydate == 2) {  
            week = ”周一”;  
        } else if (mydate == 3) {  
            week = ”周二”;  
        } else if (mydate == 4) {  
            week = ”周三”;  
        } else if (mydate == 5) {  
            week = ”周四”;  
        } else if (mydate == 6) {  
            week = ”周五”;  
        } else if (mydate == 7) {  
            week = ”周六”;  
        }  
        return week;  
    }  
  
    // 并用分割符把时间分成时间数组  
    /** 
     * 调用此方法输入所要转换的时间戳输入例如(1402733340)输出(”2014-06-14-16-09-00”) 
     *  
     * @param time 
     * @return 
     */  
    public String timesOne(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy-MM-dd-HH-mm-ss”);  
        @SuppressWarnings(“unused”)  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        return times;  
  
    }  
  
    public static String timesTwo(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy-MM-dd”);  
        @SuppressWarnings(“unused”)  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        return times;  
  
    }  
  
    /** 
     * 并用分割符把时间分成时间数组 
     *  
     * @param time 
     * @return 
     */  
    public static String[] timestamp(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy年MM月dd日HH时mm分ss秒”);  
        @SuppressWarnings(“unused”)  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        String[] fenge = times.split(”[年月日时分秒]”);  
        return fenge;  
    }  
  
    /** 
     * 根据传递的类型格式化时间 
     *  
     * @param str 
     * @param type 
     *            例如:yy-MM-dd 
     * @return 
     */  
    public static String getDateTimeByMillisecond(String str, String type) {  
  
        Date date = new Date(Long.valueOf(str));  
  
        SimpleDateFormat format = new SimpleDateFormat(type);  
  
        String time = format.format(date);  
  
        return time;  
    }  
  
    /** 
     * 分割符把时间分成时间数组 
     *  
     * @param time 
     * @return 
     */  
    public String[] division(String time) {  
  
        String[] fenge = time.split(”[年月日时分秒]”);  
  
        return fenge;  
  
    }  
  
    /** 
     * 输入时间戳变星期 
     *  
     * @param time 
     * @return 
     */  
    public static String changeweek(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy年MM月dd日HH时mm分ss秒”);  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        Date date = null;  
        int mydate = 0;  
        String week = null;  
        try {  
            date = sdr.parse(times);  
            Calendar cd = Calendar.getInstance();  
            cd.setTime(date);  
            mydate = cd.get(Calendar.DAY_OF_WEEK);  
            // 获取指定日期转换成星期几  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        if (mydate == 1) {  
            week = ”星期日”;  
        } else if (mydate == 2) {  
            week = ”星期一”;  
        } else if (mydate == 3) {  
            week = ”星期二”;  
        } else if (mydate == 4) {  
            week = ”星期三”;  
        } else if (mydate == 5) {  
            week = ”星期四”;  
        } else if (mydate == 6) {  
            week = ”星期五”;  
        } else if (mydate == 7) {  
            week = ”星期六”;  
        }  
        return week;  
  
    }  
  
    /** 
     * 获取日期和星期 例如:2014-11-13 11:00 星期一 
     *  
     * @param time 
     * @param type 
     * @return 
     */  
    public static String getDateAndWeek(String time, String type) {  
        return getDateTimeByMillisecond(time + “000”, type) + “  ”  
                + changeweekOne(time);  
    }  
  
    /** 
     * 输入时间戳变星期 
     *  
     * @param time 
     * @return 
     */  
    public static String changeweekOne(String time) {  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy-MM-dd-HH-mm-ss”);  
        long lcc = Long.valueOf(time);  
        int i = Integer.parseInt(time);  
        String times = sdr.format(new Date(i * 1000L));  
        Date date = null;  
        int mydate = 0;  
        String week = null;  
        try {  
            date = sdr.parse(times);  
            Calendar cd = Calendar.getInstance();  
            cd.setTime(date);  
            mydate = cd.get(Calendar.DAY_OF_WEEK);  
            // 获取指定日期转换成星期几  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        if (mydate == 1) {  
            week = ”星期日”;  
        } else if (mydate == 2) {  
            week = ”星期一”;  
        } else if (mydate == 3) {  
            week = ”星期二”;  
        } else if (mydate == 4) {  
            week = ”星期三”;  
        } else if (mydate == 5) {  
            week = ”星期四”;  
        } else if (mydate == 6) {  
            week = ”星期五”;  
        } else if (mydate == 7) {  
            week = ”星期六”;  
        }  
        return week;  
  
    }  
  
    /** 
     * 获取当前时间 
     *  
     * @return 
     */  
    public static String getCurrentTime() {  
        SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm”);  
        return sdf.format(new java.util.Date());  
    }  
      
    /** 
     * 输入日期如(2014年06月14日16时09分00秒)返回(星期数) 
     *  
     * @param time 
     * @return 
     */  
    public String week(String time) {  
        Date date = null;  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy年MM月dd日HH时mm分ss秒”);  
        int mydate = 0;  
        String week = null;  
        try {  
            date = sdr.parse(time);  
            Calendar cd = Calendar.getInstance();  
            cd.setTime(date);  
            mydate = cd.get(Calendar.DAY_OF_WEEK);  
            // 获取指定日期转换成星期几  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        if (mydate == 1) {  
            week = ”星期日”;  
        } else if (mydate == 2) {  
            week = ”星期一”;  
        } else if (mydate == 3) {  
            week = ”星期二”;  
        } else if (mydate == 4) {  
            week = ”星期三”;  
        } else if (mydate == 5) {  
            week = ”星期四”;  
        } else if (mydate == 6) {  
            week = ”星期五”;  
        } else if (mydate == 7) {  
            week = ”星期六”;  
        }  
        return week;  
    }  
  
    /** 
     * 输入日期如(2014-06-14-16-09-00)返回(星期数) 
     *  
     * @param time 
     * @return 
     */  
    public String weekOne(String time) {  
        Date date = null;  
        SimpleDateFormat sdr = new SimpleDateFormat(“yyyy-MM-dd-HH-mm-ss”);  
        int mydate = 0;  
        String week = null;  
        try {  
            date = sdr.parse(time);  
            Calendar cd = Calendar.getInstance();  
            cd.setTime(date);  
            mydate = cd.get(Calendar.DAY_OF_WEEK);  
            // 获取指定日期转换成星期几  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        if (mydate == 1) {  
            week = ”星期日”;  
        } else if (mydate == 2) {  
            week = ”星期一”;  
        } else if (mydate == 3) {  
            week = ”星期二”;  
        } else if (mydate == 4) {  
            week = ”星期三”;  
        } else if (mydate == 5) {  
            week = ”星期四”;  
        } else if (mydate == 6) {  
            week = ”星期五”;  
        } else if (mydate == 7) {  
            week = ”星期六”;  
        }  
        return week;  
    }  
}  

3.Android获取时间戳,以及将时间戳转换为时间

代码如下:

package com.androidtimestampdemo;  
  
import java.text.SimpleDateFormat;  
import java.util.Calendar;  
import java.util.Date;  
import java.util.Locale;  
  
import android.app.Activity;  
import android.os.Bundle;  
import android.util.Log;  
  
public class MainActivity extends Activity {  
    private long timecurrentTimeMillis;  
    private long timeGetTime;  
    private long timeSeconds;  
    private long timeMillis;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
  
        init();  
    }  
  
    private void init() {  
        /** 
         * 以下是获取现在的系统时间戳的几种方法,实际开发中可能需要服务端返回所需的时间戳 ; 
         * 但是实际开发中服务端返回的时间戳可能是字符串等,需要转换为long等,可采用如下方法直接转换: 
         * Integer.parseInt(String s) Long.parseLong(String s) 
         * Float.parseFloat(String s) Double.parseDouble(String s) 
         */  
        timecurrentTimeMillis = System.currentTimeMillis();  
        timeGetTime = new Date().getTime();  
        timeSeconds = System.currentTimeMillis();  
        timeMillis = Calendar.getInstance().getTimeInMillis();  
        /** 
         * 通过打印信息可以看到,这几种获取系统时间的时间戳几乎是一样的。 
         */  
        Log.d("zhongyao", "timecurrentTimeMillis" + timecurrentTimeMillis  
                + "@@@" + "timeGetTime" + timeGetTime + "@@@timeSeconds"  
                + timeSeconds + "timeMillis" + timeMillis);  
        /** 
         * 时间戳转换成具体时间形式 
         */  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日",  
                Locale.getDefault());  
        String time1 = sdf.format(timeSeconds);  
        String time2 = sdf.format(timeGetTime);  
        Log.d("zhongyao", timeSeconds + "  现在的时间1->:" + time1);  
        Log.d("zhongyao", timeGetTime + "  现在的时间2-->:" + time2);  
  
        SimpleDateFormat sdfTwo = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒E",  
                Locale.getDefault());  
        String time11 = sdfTwo.format(timeSeconds);  
        String time22 = sdfTwo.format(timeGetTime);  
        Log.d("zhongyao", timeSeconds + "  现在的时间11->:" + time11);  
        Log.d("zhongyao", timeGetTime + "  现在的时间22-->:" + time22);  
          
        /** 
         * 而最常用的: 
         * 由于服务端返回的一般是UNIX时间戳,所以需要把UNIX时间戳timeStamp转换成固定格式的字符串 
         */  
        String result = formatData("yyyy-MM-dd", 1414994617);  
        Log.d("zhongyao", result);  
  
    }  
  
    public static String formatData(String dataFormat, long timeStamp) {  
        if (timeStamp == 0) {  
            return "";  
        }  
        timeStamp = timeStamp * 1000;  
        String result = "";  
        SimpleDateFormat format = new SimpleDateFormat(dataFormat);  
        result = format.format(new Date(timeStamp));  
        return result;  
    }  
}  

到此这篇关于Android实现获取当前时间并转为时间戳的文章就介绍到这了,更多相关Android获取当前时间内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文