注:轉(zhuǎn)發(fā)請注明原地址:https://www.niwoxuexi.com/blog/android/article/170...
在Android開發(fā)過程中仔沿,經(jīng)常會遇到日期的各種格式轉(zhuǎn)換掐禁,主要使用SimpleDateFormat這個類來實現(xiàn)谐檀,掌握了這個類,可以轉(zhuǎn)換任何你想要的各種格式。
常見的日期格式:
- 日期格式:String dateString = "2017-06-20 10:30:30" 對應(yīng)的格式:String pattern = "yyyy-MM-dd HH:mm:ss";
- 日期格式:String dateString = "2017-06-20" 對應(yīng)的格式:String pattern = "yyyy-MM-dd";
- 日期格式:String dateString = "2017年06月20日 10時30分30秒 對應(yīng)的格式:String pattern = "yyyy年MM月dd日 HH時mm分ss秒";
- 日期格式:String dateString = "2017年06月20日" 對應(yīng)的格式:String pattern = "yyyy年MM月dd日";
下面是幾種情況(其中pattern 根據(jù)上面的選擇,如果需要其他的格式,自己去網(wǎng)上查吧)
一底燎、獲取系統(tǒng)時間戳
public long getCurTimeLong(){
long time=System.currentTimeMillis();
return time;
}
二、獲取當(dāng)前時間
public static String getCurDate(String pattern){
SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
return sDateFormat.format(new java.util.Date());
}
三弹砚、時間戳轉(zhuǎn)換成字符竄
public static String getDateToString(long milSecond, String pattern) {
Date date = new Date(milSecond);
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.format(date);
}
四双仍、將字符串轉(zhuǎn)為時間戳
public static long getStringToDate(String dateString, String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Date date = new Date();
try{
date = dateFormat.parse(dateString);
} catch(ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date.getTime();
}
工具類代碼:
package com.niwoxuexi.testdemo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by niwoxuexi.com on 2017/6/23.
*/
public class DateUtil {
/**
* 獲取系統(tǒng)時間戳
* @return
*/
public long getCurTimeLong(){
long time=System.currentTimeMillis();
return time;
}
/**
* 獲取當(dāng)前時間
* @param pattern
* @return
*/
public static String getCurDate(String pattern){
SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
return sDateFormat.format(new java.util.Date());
}
/**
* 時間戳轉(zhuǎn)換成字符竄
* @param milSecond
* @param pattern
* @return
*/
public static String getDateToString(long milSecond, String pattern) {
Date date = new Date(milSecond);
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.format(date);
}
/**
* 將字符串轉(zhuǎn)為時間戳
* @param dateString
* @param pattern
* @return
*/
public static long getStringToDate(String dateString, String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Date date = new Date();
try{
date = dateFormat.parse(dateString);
} catch(ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date.getTime();
}
}