android实现日期时间的显示
前言:这里介绍两种日期显示的方法!
放张简陋效果图(但可实现的效果远不止如此)
方法一:
——该方法可显示当前时间,以及日期切换,主要是自己封装的方法,具体可参考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);
}