我写了下面的代码

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()+"";

其他回答

试试这个链接的代码,这是绝对正确的答案,所有的情况下,所有的日期和时间。或根据应用程序的需要和要求自定义日期和时间。

试试这个链接。试试这个链接

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()+"";
Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);

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

这是最好的答案……

您可以使用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

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