前言:這裏介紹兩種日期顯示的方法!
放張簡陋效果圖(但可實現的效果遠不止如此)
方法一:
——該方法可顯示當前時間,以及日期切換,主要是自己封裝的方法,具體可參考JDK API
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲取組件
TextView dayBefore = findViewById(R.id.day_before);
TextView dayNow = findViewById(R.id.day_now);
TextView dayAfter = findViewById(R.id.day_after);
//調用方法獲取時間
String timeNow = getNowDay("yyyy-MM-dd HH:mm:ss");
String timeBefore = getDayBefore("2019-02-25 00:00:00");
String timeAfter = getDayAfter("2019-02-25 00:00:00");
//將獲取的時間賦值給組件
dayNow.setText("今日:"+timeNow);
dayBefore.setText("昨日:"+timeBefore);
dayAfter.setText("明日:"+timeAfter);
}
/**
*獲取當前時間
* @param timeFormat 時間格式
* @return 時間文本
*/
public String getNowDay(String timeFormat){
/**
* SimpleDateFormat 是一個以與語言環境有關的方式來格式化和解析日期的具體類(java.text.SimpleDateFormat)。
* 它允許進行格式化(日期 -> 文本)、解析(文本 -> 日期)和規範化。
*/
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(timeFormat);
String dateString = simpleDateFormat.format(new Date()); //將給定的 Date 格式化爲日期/時間字符串
return dateString;
}
/**
* 獲得指定日期的前一天
* @param specifiedDay 指定日期
* @return
*/
public static String getDayBefore(String specifiedDay) {
Calendar c = Calendar.getInstance();
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day = c.get(Calendar.DATE);//DATE指示一個月中的某天
c.set(Calendar.DATE, day - 1);
String dayBefore = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c
.getTime());
return dayBefore;
}
/**
* 獲得指定日期的後一天
* @param specifiedDay 指定日期
* @return
*/
public static String getDayAfter(String specifiedDay) {
Calendar c = Calendar.getInstance();
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(specifiedDay);
} catch (ParseException e) {
e.printStackTrace();
}
c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day + 1);
String dayAfter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(c.getTime());
return dayAfter;
}
方法二:(強烈推薦)
——該方法引用第三方工具,代碼量少且可實現更加豐富的時間顯示功能,如圖(只截取部分),詳情請點擊Hutool文檔
同樣顯示今日昨日明日的時間,看使用工具有多簡單就可完成!
首先,android要在build.gradle引入jar包:
dependencies {
implementation 'cn.hutool:hutool-all:4.4.5'
}
然後僅僅三行代碼就可搞定,而不用像方法一那樣封裝三個獲取時間的方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲取組件
TextView dayBefore = findViewById(R.id.day_before);
TextView dayNow = findViewById(R.id.day_now);
TextView dayAfter = findViewById(R.id.day_after);
//當前時間字符串,格式:yyyy-MM-dd HH:mm:ss
String now = DateUtil.now();
//昨天
String yesterday = DateUtil.yesterday().toString();
//明天
String tomorrow = DateUtil.tomorrow().toString();
//將獲取的時間賦值給組件
dayNow.setText("今日:"+now);
dayBefore.setText("昨日:"+yesterday);
dayAfter.setText("明日:"+tomorrow);
}