Android与IOS中获取时间戳的方法

什么是时间戳?

时间戳是自 1970 年 1 月 1 日(00:00:00 GMT)至当前时间的总秒数。它也被称为 Unix 时间戳(Unix Timestamp)。

iOS中获取毫秒时间戳

转载地址:原地址链接
获取方法:

UInt64 recordTime = [[NSDate date] timeIntervalSince1970]*1000;

首先 [[NSDate date] timeIntervalSince1970] 是可以获取到后面的毫秒 微秒的 ,只是在保存的时候省略掉了, 如一个时间戳不省略的情况下为 1395399556.862046 ,省略掉后为一般所见 1395399556 。
所以想取得毫秒时用获取到的时间戳 * 1000 ,想取得微秒时 用取到的时间戳 * 1000 * 1000 。

NSDateFormatter * formatter = [[NSDateFormatter alloc ] init];  
[formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];    
NSString *date =  [formatter stringFromDate:[NSDate date]];  
NSString *timeLocal = [[NSString alloc] initWithFormat:@"%@", date]; 
NSLog(@"%@", timeLocal);

Android 中获取时间戳的方法

转载链接: 原文链接
1.获取当前时间

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

2.获取系统时间

//取得系统时间  
//1。  
long time=System.currentTimeMillis();  

//2。  
final Calendar mCalendar=Calendar.getInstance();  
mCalendar.setTimeInMillis(time);  
取得小时:mHour=mCalendar.get(Calendar.HOUR);  
取得分钟:mMinuts=mCalendar.get(Calendar.MINUTE);  

//3。  
Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料  
t.setToNow(); // 取得系统时间。  
int year = t.year;  
int month = t.month;  
int date = t.monthDay;  
int hour = t.hour;    // 0-23  

//4。  
DateFormat df = new SimpleDateFormat("HH:mm:ss");  
df.format(new Date());  

3.时间工具类

import android.util.Log;        
import java.text.ParseException;        
import java.text.SimpleDateFormat;        
import java.util.Calendar;        
import java.util.Date;        


public class TimeUtils {        

    /**    
     * 获取当前时间    
     * @return    
     */        
    public static String getNowTime(){        
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");        
        Date date = new Date(System.currentTimeMillis());        
        return simpleDateFormat.format(date);        
    }        
    /**    
     * 获取时间戳    
     *    
     * @return 获取时间戳    
     */        
    public static String getTimeString() {        
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");        
        Calendar calendar = Calendar.getInstance();        
        return df.format(calendar.getTime());        
    }        
    /**    
     * 时间转换为时间戳    
     * @param time:需要转换的时间    
     * @return    
     */        
    public static String dateToStamp(String time)  {        
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        
        Date date = null;        
        try {        
            date = simpleDateFormat.parse(time);        
        } catch (ParseException e) {        
            e.printStackTrace();        
        }        
        long ts = date.getTime();        
        return String.valueOf(ts);        
    }        

    /**    
     * 时间戳转换为字符串    
     * @param time:时间戳    
     * @return    
     */        
    public static String times(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 hour hour=-1为上一个小时,hour=1为下一个小时    
     * @return    
     */        
    public static String getLongTime(int hour){        
        Calendar c = Calendar.getInstance(); // 当时的日期和时间        
        int h; // 需要更改的小时        
        h = c.get(Calendar.HOUR_OF_DAY) - hour;        
        c.set(Calendar.HOUR_OF_DAY, h);        
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");        
        Log.v("time",df.format(c.getTime()));        
        return df.format(c.getTime());        
    }      
    /**   
     * 比较时间大小   
     * @param str1:要比较的时间   
     * @param str2:要比较的时间   
     * @return   
     */      
    public static boolean isDateOneBigger(String str1, String str2) {      
        boolean isBigger = false;      
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");      
        Date dt1 = null;      
        Date dt2 = null;      
        try {      
            dt1 = sdf.parse(str1);      
            dt2 = sdf.parse(str2);      
        } catch (ParseException e) {      
            e.printStackTrace();      
        }      
        if (dt1.getTime() > dt2.getTime()) {      
            isBigger = true;      
        } else if (dt1.getTime() < dt2.getTime()) {      
            isBigger = false;      
        }      
        return isBigger;      
    }      
}        
  /**  
  * 当地时间 ---> UTC时间  
  * @return  
  */    
 public static String Local2UTC(){    
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    
     sdf.setTimeZone(TimeZone.getTimeZone("gmt"));    
     String gmtTime = sdf.format(new Date());    
     return gmtTime;    
 }    

  /**  
  * UTC时间 ---> 当地时间  
  * @param utcTime   UTC时间  
  * @return  
  */    
 public static String utc2Local(String utcTime) {    
     SimpleDateFormat utcFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//UTC时间格式    
     utcFormater.setTimeZone(TimeZone.getTimeZone("UTC"));    
     Date gpsUTCDate = null;    
     try {    
         gpsUTCDate = utcFormater.parse(utcTime);    
     } catch (ParseException e) {    
         e.printStackTrace();    
     }    
     SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//当地时间格式    
     localFormater.setTimeZone(TimeZone.getDefault());    
     String localTime = localFormater.format(gpsUTCDate.getTime());    
     return localTime;    
 }   

使用案例:

package com.example.time;  

import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.TimeZone;  

import android.app.Activity;  
import android.os.Bundle;  

public class MainActivity extends Activity {  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  

        new Thread(){  
            public void run() {  
                String time = Local2UTC("2018-03-19 19:41:44");  
                System.out.println("time"+time);  
            };  
        }.start();  
    }  
    /** 
     * 将本地时间转为UTC时间 
     * @param strDate:需要转化的date 
     * @return 
     */  
    public String Local2UTC(String strDate){    
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
         String gmtTime = "";  
         sdf.setTimeZone(TimeZone.getTimeZone("gmt"));    
         gmtTime = sdf.format(stringToDate(strDate, "yyyy-MM-dd HH:mm:ss"));  
         return gmtTime;    
     }    
    /** 
     * 将string类型转换为date类型 
     * @param strTime:要转换的string类型的时间,时间格式必须要与formatType的时间格式相同 
     * @param formatType:要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 
     * @return 
     */  
    private Date stringToDate(String strTime, String formatType){  
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);  
        Date date = null;  
        try {  
            date = (Date) formatter.parse(strTime);  
        } catch (ParseException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        return date;  
    }  

}  

Unity中获取时间戳的方法

转载地址:原文链接

  /// 获取当前时间戳
    /// </summary>
    /// <param name="bflag">为真时获取10位时间戳,为假时获取13位时间戳.</param>
    /// <returns></returns>
    public static long GetTimeStamp(bool bflag = true)
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        long ret;
        if (bflag)
            ret = Convert.ToInt64(ts.TotalSeconds);
        else
            ret = Convert.ToInt64(ts.TotalMilliseconds);
        return ret;
    }


    static DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
    public static string NormalizeTimpstamp0(long timpStamp)
    {
        long unixTime = timpStamp * 10000000L;
        TimeSpan toNow = new TimeSpan(unixTime);
        DateTime dt = dtStart.Add(toNow);
        return dt.ToString("yyyy-MM-dd");
    }


    /// <summary>
    /// 时钟式倒计时
    /// </summary>
    /// <param name="second"></param>
    /// <returns></returns>
    public string GetSecondString(int second)
    {
        return string.Format("{0:D2}", second / 3600) + string.Format("{0:D2}", second % 3600 / 60) + ":" + string.Format("{0:D2}", second % 60);
    }


    /// 将Unix时间戳转换为DateTime类型时间
    /// </summary>
    /// <param name="d">double 型数字</param>
    /// <returns>DateTime</returns>
    public static System.DateTime ConvertIntDateTime(double d)
    {
        System.DateTime time = System.DateTime.MinValue;
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0));
        Debug.Log(startTime);
        time = startTime.AddSeconds(d);
        return time;
    }


    /// <summary>
    /// 将c# DateTime时间格式转换为Unix时间戳格式
    /// </summary>
    /// <param name="time">时间</param>
    /// <returns>double</returns>
    public static double ConvertDateTimeInt(System.DateTime time)
    {
        double intResult = 0;
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        intResult = (time - startTime).TotalSeconds;
        return intResult;
    }


    /// <summary>
    /// 日期转换成unix时间戳
    /// </summary>
    /// <param name="dateTime"></param>
    /// <returns></returns>
    public static long DateTimeToUnixTimestamp(DateTime dateTime)
    {
        var start = new DateTime(1970, 1, 1, 0, 0, 0, dateTime.Kind);
        return Convert.ToInt64((dateTime - start).TotalSeconds);
    }


    /// <summary>
    /// unix时间戳转换成日期
    /// </summary>
    /// <param name="unixTimeStamp">时间戳(秒)</param>
    /// <returns></returns>
    public static DateTime UnixTimestampToDateTime(DateTime target, long timestamp)
    {
        DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);
        return start.AddSeconds(timestamp);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python获取时间方法有多种。其一种方法是使用time模块的time()函数,该函数返回从1970年1月1日午夜到当前时间的秒数时间。可以使用以下代码获取时间: ```python import time timestamp = int(time.time()) print(timestamp) ``` 另一种方法是使用time()函数并乘以1000来获取毫秒时间: ```python import time timestamp = int(time.time() * 1000) print(timestamp) ``` 还可以使用time()函数并乘以1000000来获取微秒时间: ```python import time timestamp = int(time.time() * 1000000) print(timestamp) ``` 这些方法可以方便地获取当前时间时间,可以根据需要选择使用不同的精度。引用<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python获取时间](https://blog.csdn.net/qq_34445574/article/details/128328264)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [【python】python获取时间](https://blog.csdn.net/cw_huang/article/details/119954674)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Python获取时间代码实例](https://download.csdn.net/download/weixin_38653694/12859258)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值