📅  最后修改于: 2023-12-03 15:13:21.436000             🧑  作者: Mango
在 Android 应用开发中,我们经常需要处理日期和时间。Android 提供了一套强大的日期和时间格式化工具,使得我们可以方便地处理和显示日期和时间。
Android 提供了两个主要的类来处理日期和时间:Date
和 Calendar
。Date
类用于表示一个日期和时间点,而 Calendar
类则提供了更为灵活的日期和时间操作。
除此之外,Android 还提供了用于格式化日期和时间的类:SimpleDateFormat
、DateFormat
和 TimeFormat
。
SimpleDateFormat
是一个用于格式化和解析日期和时间的类。它使用一些预定义的模式来指定日期和时间的显示格式。
以下是一个简单的例子,演示了如何使用 SimpleDateFormat
格式化日期和时间:
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(new Date());
TextView textView = findViewById(R.id.textView);
textView.setText(formattedDate);
}
}
上面的代码将当前日期和时间格式化为 "yyyy-MM-dd HH:mm:ss" 的形式,并将其显示在一个 TextView
中。
以下是一些常用的日期和时间模式:
yyyy
(4 位数),yy
(2 位数)MM
(两位数),M
(一位数),MMMM
(带有月份名)dd
(两位数),d
(一位数)HH
(24 小时制),hh
(12 小时制)mm
ss
a
在 SimpleDateFormat
中,你还可以使用特殊字符 '
来转义显示字符本身。
以下是一些示例代码,展示了日期和时间格式化的不同情况:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2022-01-01 12:00:00");
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String dayOfWeek = sdf.format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
String monthName = sdf.format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
String customFormat = sdf.format(new Date());
Calendar
类是一个用于处理日期和时间的强大工具。它提供了各种方法来操作和计算日期和时间。
以下是一些常用的 Calendar
操作:
Calendar calendar = Calendar.getInstance();
Date currentDate = calendar.getTime();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2022);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 7); // 添加 7 天
calendar.add(Calendar.HOUR_OF_DAY, -3); // 减去 3 小时
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH); // 0 表示一月
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
Android 中的日期和时间格式化是非常重要的,特别是在显示和解析用户输入、展示通知、生成文件名等场景下。本文介绍了使用 SimpleDateFormat
进行格式化和解析,以及使用 Calendar
类进行日期和时间操作的方法。
了解和掌握这些工具可以帮助程序员处理各种与日期和时间相关的任务,并提供更好的用户体验。