欧亚之窗 發表於 2025-9-30 10:00:37

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

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>1. 获取年月日时分秒</li><li>2. 区分系统时间是24小时制还是12小时制</li><li>3. 字符串转时间戳</li><li>4. 时间戳转字符串</li><li>方法补充</li></ul></div><p>在项目开发中,难免会遇到使用当前时间,比如实现网络请求上传报文、预约、日历等功能。</p>
<p class="maodian"></p><h2>1. 获取年月日时分秒</h2>
<p>在获取时间之前,首先要引入SimpleDateFormat:</p>
<div class="jb51code"><pre class="brush:java;">import java.text.SimpleDateFormat;
</pre></div>
<p>实现代码:</p>
<div class="jb51code"><pre class="brush:java;">SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());//获取当前时间      
String str= formatter.format(curDate);
</pre></div>
<p>str就是我们需要的时间,代码中(&ldquo;yyyy年MM月dd日 HH:mm:ss&rdquo;)这个时间的样式是可以根据我们的需求进行修改的,比如:20170901112253 ==&gt; (&ldquo;yyyyMMddHHmmss&rdquo;)</p>
<p>如果只想获取年月,代码如下:</p>
<div class="jb51code"><pre class="brush:java;">SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
Date curDate = new Date(System.currentTimeMillis());//获取当前时间      
String str= formatter.format(curDate);
</pre></div>
<p class="maodian"></p><h2>2. 区分系统时间是24小时制还是12小时制</h2>
<p>在获取之前,首先要引入ContentResolver:</p>
<div class="jb51code"><pre class="brush:java;">import android.content.ContentResolver;
</pre></div>
<p>代码如下:</p>
<div class="jb51code"><pre class="brush:java;">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");
}
</pre></div>
<p class="maodian"></p><h2>3. 字符串转时间戳</h2>
<p>代码如下:</p>
<div class="jb51code"><pre class="brush:java;">    //字符串转时间戳
    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;
    }
</pre></div>
<p class="maodian"></p><h2>4. 时间戳转字符串</h2>
<p>代码如下:</p>
<div class="jb51code"><pre class="brush:java;">    //时间戳转字符串
    public static String getStrTime(String timeStamp){
      String timeString = null;
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm");
      longl = Long.valueOf(timeStamp);
      timeString = sdf.format(new Date(l));//单位秒
      return timeString;
    }
</pre></div>
<p class="maodian"></p><h2>方法补充</h2>
<p>1.Android中获取当前时间戳</p>
<p>Android获取时间戳的四种方法如下:</p>
<div class="jb51code"><pre class="brush:java;">long timecurrentTimeMillis = System.currentTimeMillis();
long timeGetTime =new Date().getTime();
long timeSeconds = System.currentTimeMillis();
long timeMillis = Calendar.getInstance().getTimeInMillis();

Log.d(TAG, "当前时间戳1---&gt;:"+timecurrentTimeMillis);
Log.d(TAG, "当前时间戳2---&gt;:"+timeGetTime);
Log.d(TAG, "当前时间戳3---&gt;:"+timeSeconds);
Log.d(TAG, "当前时间戳4---&gt;:"+timeMillis);</pre></div>
<p>2.Android实现 时间戳与日期间的各种互换的时间工具类</p>
<p>完整代码如下:</p>
<div class="jb51code"><pre class="brush:java;">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-1416: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;
    }
}</pre></div>
<p>3.Android获取时间戳,以及将时间戳转换为时间</p>
<p>代码如下:</p>
<div class="jb51code"><pre class="brush:java;">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-&gt;:" + time1);
      Log.d("zhongyao", timeGetTime + "现在的时间2--&gt;:" + 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-&gt;:" + time11);
      Log.d("zhongyao", timeGetTime + "现在的时间22--&gt;:" + 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;
    }
}</pre></div>
<p>到此这篇关于Android实现获取当前时间并转为时间戳的文章就介绍到这了,更多相关Android获取当前时间内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>Android获取所在时区时间的两种方式</li><li>Android开发获取当前系统日期和时间功能示例</li><li>Android关于获取时间的记录(小结)</li><li>Android 获取时间实例代码</li><li>Android进阶之使用时间戳计算时间差</li><li>Android编程计算函数时间戳的相关方法总结</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: Android实现获取当前时间并转为时间戳