我写了下面的代码

Date d = new Date();
CharSequence s  = DateFormat.format("MMMM d, yyyy ", d.getTime());

我想要当前日期的字符串格式,比如

28-Dec-2011

这样我就可以把它设置为TextView。


当前回答

我提供的是现代的答案。

java。time和ThreeTenABP

获取当前日期:

    LocalDate today = LocalDate.now(ZoneId.of("America/Hermosillo"));

这将为您提供一个LocalDate对象,您应该使用该对象在程序中保存日期。LocalDate是一个没有时间的日期。

只有当你需要向用户显示日期时,将其格式化为适合用户语言环境的字符串:

    DateTimeFormatter userFormatter
            = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
    System.out.println(today.format(userFormatter));

当我今天在美国英语环境中运行这个片段时,输出是:

2019年7月13日

如果您希望它更短,请指定FormatStyle。MEDIUM或甚至FormatStyle.SHORT。DateTimeFormatter。ofLocalizedDate使用默认格式区域设置,因此重点是它将提供适合该区域设置的输出,不同的区域设置会有所不同。

如果你的用户对输出格式有非常特殊的要求,使用格式模式字符串:

    DateTimeFormatter userFormatter = DateTimeFormatter.ofPattern(
            "d-MMM-u", Locale.forLanguageTag("ar-AE"));

2019 年 7 月 13 日

我正在使用和推荐java。时间,现代Java日期和时间API。在问题和/或许多其他答案中使用的DateFormat, SimpleDateFormat,日期和日历,设计很差,已经过时了。和java。和时间一起工作真是太好了。

问:我可以使用java吗?Android的时间?

是的,java。time在新旧安卓设备上都能很好地运行。它只需要至少Java 6。

在Java 8及以后版本和更新的Android设备上(从API级别26开始),内置了现代API。 在Java 6和7中获得ThreeTen Backport,现代类的后端口(JSR 310的ThreeTen;参见底部的链接)。 在(旧的)Android上使用ThreeTen Backport的Android版本。叫做ThreeTenABP。并确保从org.three .bp导入带有子包的日期和时间类。

链接

Oracle教程:Date Time解释如何使用java.time。 Java规范请求(JSR) 310,其中Java。时间是最早被描述的。 ThreeTen Backport项目,java的Backport。Java 6和7的时间(JSR-310的ThreeTen)。 ThreeTenABP, Android版的ThreeTen Backport 问:如何在Android项目中使用ThreeTenABP,并有一个非常详细的解释。

其他回答

Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
String date = day + "/" + (month + 1) + "/" + year;

Log.i("TAG", "--->" + date);
CharSequence s  = DateFormat.getDateInstance().format("MMMM d, yyyy ");

首先需要一个实例

这与android无关,因为它是基于java的,所以你可以使用

private String getDateTime() { 
   DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
   Date date = new Date(); 
   return dateFormat.format(date); 
}

您可以使用SimpleDateFormat类将日期格式化为所需的格式。

只要检查这个链接,你就可以得到你的例子的想法。

例如:

String dateStr = "04/05/2010"; 
 
SimpleDateFormat curFormater = new SimpleDateFormat("dd/MM/yyyy"); 
Date dateObj = curFormater.parse(dateStr); 
SimpleDateFormat postFormater = new SimpleDateFormat("MMMM dd, yyyy"); 
 
String newDateStr = postFormater.format(dateObj); 

更新:

详细的示例在这里,我建议您通过这个示例并理解SimpleDateFormat类的概念。

最终解决方案:

Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);

SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault());
String formattedDate = df.format(c);

只需一行代码获得简单的日期格式:

SimpleDateFormat.getDateInstance().format(Date())

产出:2020年5月18日

SimpleDateFormat.getDateTimeInstance().format(Date())

上午11:00:39

SimpleDateFormat.getTimeInstance().format(Date())

输出:11:00:39 AM

希望这个答案足以得到这个日期和时间格式…:)