java - 在 TextView 的 setText 之前更改日期格式

标签 java android date

我使用 DatePicker 来选择日期。一切顺利。但问题是格式化日期。

// display current date
public void setCurrentDateOnView() {

    tvDisplayDate = (TextView) findViewById(R.id.tvDate);

    final Calendar c = Calendar.getInstance();
    year = c.get(Calendar.YEAR);
    month = c.get(Calendar.MONTH);
    day = c.get(Calendar.DAY_OF_MONTH);

    // set current date into textview    
    tvDisplayDate.setText(new StringBuilder().append(year).append("-").append(month + 1).append("-").append(day).append(" "));
    // Month is 0 based, just add 1

}

根据代码,我得到了输出:2016-8-22 但 我的预期输出是 2016-08-22(我想要这样的月份 08)

谢谢, 问候, 卡尔西。

最佳答案

使用简单日期格式:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
tvDisplayDate.setText(sdf.format(c.getTime()));

有关 SimpleDateFormat 的更多信息,请参阅官方 documentation

关于java - 在 TextView 的 setText 之前更改日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39072608/

相关文章:

java - Java 中对 0xFF 使用按位与运算符的原因

java - 为什么我的线性布局与 ListView 中的父级高度不匹配?

Java - 如何限制从特定方法调用方法

机器人: fragment 的 Recyclerview?

php - 实时和日期插入MySQL服务器

java - 带有套接字的 ObjectInputStreams 的其他问题

java - 按照 Android 构建说明 - 模拟器失败并显示 "No initial system image for this configuration"

android - 如何将滤色器应用于具有所有子项的 View

r - 使用 R 测试日期是否出现在多个日期范围内

javascript - Fullcalendar 将当前日期作为开始日期,并且不显示之前的日期