在項(xiàng)目開發(fā)中,難免會(huì)遇到使用當(dāng)前時(shí)間,比如實(shí)現(xiàn)網(wǎng)絡(luò)請(qǐng)求上傳報(bào)文、預(yù)約、日歷等功能。
1. 獲取年月日時(shí)分秒
在獲取時(shí)間之前,首先要引入SimpleDateFormat:
import java.text.SimpleDateFormat;
實(shí)現(xiàn)代碼:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date curDate = new Date(System.currentTimeMillis());//獲取當(dāng)前時(shí)間
String str = formatter.format(curDate);
str就是我們需要的時(shí)間,代碼中("yyyy年MM月dd日 HH:mm:ss")這個(gè)時(shí)間的樣式是可以根據(jù)我們的需求進(jìn)行修改的,比如:
20170901112253 ==> ("yyyyMMddHHmmss")
如果只想獲取年月,代碼如下:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
Date curDate = new Date(System.currentTimeMillis());//獲取當(dāng)前時(shí)間
String str = formatter.format(curDate);
2. 區(qū)分系統(tǒng)時(shí)間是24小時(shí)制還是12小時(shí)制
在獲取之前,首先要引入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. 字符串轉(zhuǎn)時(shí)間戳
代碼如下:
//字符串轉(zhuǎn)時(shí)間戳
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. 時(shí)間戳轉(zhuǎn)字符串
代碼如下:
//時(shí)間戳轉(zhuǎn)字符串
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;
}