注:轉(zhuǎn)發(fā)請(qǐng)注明原地址:https://www.niwoxuexi.com/blog/android/article/170...
在Android開(kāi)發(fā)過(guò)程中,經(jīng)常會(huì)遇到日期的各種格式轉(zhuǎn)換,主要使用SimpleDateFormat這個(gè)類來(lái)實(shí)現(xiàn),掌握了這個(gè)類,可以轉(zhuǎn)換任何你想要的各種格式。
常見(jiàn)的日期格式:
- 日期格式:String dateString = "2017-06-20 10:30:30" 對(duì)應(yīng)的格式:String pattern = "yyyy-MM-dd HH:mm:ss";
- 日期格式:String dateString = "2017-06-20" 對(duì)應(yīng)的格式:String pattern = "yyyy-MM-dd";
- 日期格式:String dateString = "2017年06月20日 10時(shí)30分30秒 對(duì)應(yīng)的格式:String pattern = "yyyy年MM月dd日 HH時(shí)mm分ss秒";
- 日期格式:String dateString = "2017年06月20日" 對(duì)應(yīng)的格式:String pattern = "yyyy年MM月dd日";
下面是幾種情況(其中pattern 根據(jù)上面的選擇,如果需要其他的格式,自己去網(wǎng)上查吧)
一、獲取系統(tǒng)時(shí)間戳
public long getCurTimeLong(){
long time=System.currentTimeMillis();
return time;
}
二、獲取當(dāng)前時(shí)間
public static String getCurDate(String pattern){
SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
return sDateFormat.format(new java.util.Date());
}
三、時(shí)間戳轉(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)為時(shí)間戳
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)時(shí)間戳
* @return
*/
public long getCurTimeLong(){
long time=System.currentTimeMillis();
return time;
}
/**
* 獲取當(dāng)前時(shí)間
* @param pattern
* @return
*/
public static String getCurDate(String pattern){
SimpleDateFormat sDateFormat = new SimpleDateFormat(pattern);
return sDateFormat.format(new java.util.Date());
}
/**
* 時(shí)間戳轉(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)為時(shí)間戳
* @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();
}
}