我写了下面的代码
Date d = new Date();
CharSequence s = DateFormat.format("MMMM d, yyyy ", d.getTime());
我想要当前日期的字符串格式,比如
28-Dec-2011
这样我就可以把它设置为TextView。
我写了下面的代码
Date d = new Date();
CharSequence s = DateFormat.format("MMMM d, yyyy ", d.getTime());
我想要当前日期的字符串格式,比如
28-Dec-2011
这样我就可以把它设置为TextView。
当前回答
试试这个,
SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
Date myDate = new Date();
String filename = timeStampFormat.format(myDate);
其他回答
我提供的是现代的答案。
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,并有一个非常详细的解释。
我用CalendarView写了一个日历应用程序,这是我的代码:
CalendarView cal = (CalendarView) findViewById(R.id.calendar);
cal.setDate(new Date().getTime());
calendar字段是我的CalendarView。 进口:
import android.widget.CalendarView;
import java.util.Date;
我得到了当前的日期,没有错误。
我已经用过这个了:
Date What_Is_Today=Calendar.getInstance().getTime();
SimpleDateFormat Dateformat = new SimpleDateFormat("dd-MM-yyyy");
String Today=Dateformatf.format(What_Is_Today);
Toast.makeText(this,Today,Toast.LENGTH_LONG).show();
首先我得到时间,然后我声明了一个简单的日期格式(以获得日期:19-6-2018) 然后我使用format将日期更改为字符串。
public static String getcurrentDateAndTime(){
Date c = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String formattedDate = simpleDateFormat.format(c);
return formattedDate;
}
// String currentdate= getcurrentDateAndTime();
在Kotlin
https://www.programiz.com/kotlin-programming/examples/current-date-time
fun main(args: Array<String>) {
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
val formatted = current.format(formatter)
println("Current Date and Time is: $formatted")}