我写了下面的代码

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

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

28-Dec-2011

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


当前回答

LocalDateTime ldt2 = LocalDateTime.now();
String year = ldt2.getYear()+"";
String month = ldt2.getMonthValue()+"";
String date = ldt2.getDayOfMonth()+"";
String hour = ldt2.getHour()+"";
String minute = ldt2.getMinute()+"";
String secs = ldt2.getSecond()+"";

其他回答

CharSequence s  = DateFormat.getDateInstance().format("MMMM d, yyyy ");

首先需要一个实例

我提供的是现代的答案。

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,并有一个非常详细的解释。

它是简单的一行代码,用于以yyyy-MM-dd格式获取当前日期 你可以使用你想要的格式:

String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
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);
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String date = df.format(Calendar.getInstance().getTime());