Android 獲取當前時間及時間戳的互換
阿新 • • 發佈:2019-02-13
在專案開發中,難免會遇到使用當前時間,比如實現網路請求上傳報文、預約、日曆等功能。
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;
}