Android之时间戳的简单使用

本文介绍了一种在Android环境中处理时间戳的方法,包括获取系统时间戳、将时间戳转换为可读日期格式以及如何将时间转换为整数类型以便进行进一步的计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.example.test_time;


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




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


public class TimeActivity extends Activity{
	private long systemTimes;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getSystemTime();//获取系统时间戳
		String string =transationSysTime("yyyy-MM-dd HH:mm:ss",1414994617);//已知时间戳(服务器)转换为标准格式
		Log.e("TAG", "===已知时间戳"+string);
	}
	
	public void getSystemTime(){
		//获取系统时间戳的几种方式
//		systemTimes = System.currentTimeMillis();
//		systemTimes = new Date().getTime();
		systemTimes = Calendar.getInstance().getTimeInMillis();
		Log.e("TAG","===系统时间戳="+systemTimes);
		//转换为标准时间格式
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
		String time = dateFormat.format(systemTimes);
		Log.e("TAG","===系统时间="+time);
	}
	public String transationSysTime(String dateFormate,long timeType){
			if(timeType==0)
				return null;
			String result = "";
			timeType*=1000;
			SimpleDateFormat format = new SimpleDateFormat(dateFormate);
			result = format.format(new Date(timeType));
			transationTimetoInt(format,result);//将时间转换为Int类型,方便计算
			return result;
	}
	
	public void transationTimetoInt(SimpleDateFormat format,String resultStr){
		try {
			Date date = format.parse(resultStr);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			int year = calendar.get(Calendar.YEAR);
			int month = calendar.get(Calendar.MONTH);//month从0开始
			int day = calendar.get(Calendar.DAY_OF_MONTH);
			int hour = calendar.get(Calendar.HOUR_OF_DAY);
			int minute = calendar.get(Calendar.MINUTE);
			int seconds = calendar.get(Calendar.SECOND);
			Log.e("TAG","===转换为Int="+year+"年"+month+"月"+day+"日"+hour+"时"+minute+"分"+seconds+"秒");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值