我写了下面的代码

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

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

28-Dec-2011

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


当前回答

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

其他回答

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

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

试试这个,

SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
Date myDate = new Date();
String filename = timeStampFormat.format(myDate);

这是我使用的代码:

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(month + 1).append("-") // Month is 0 based, add 1
    .append(day).append("-")
    .append(year).append("   Today is :" + thursday ) );

// Set current date into datepicker
dpResult.init(year, month, day, null);

我尝试过这种方法,对我很有效。

val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault()) // pass the format pattern that you like and done.
println(df.format(Date()))
In Kotlin you can use this code : - 

Simple only need to change date format to this "dd-MM-yyyy" 
val d = Date()
val str: CharSequence = DateFormat.format("dd-MM-yyyy", d.getTime())
Log.e("", str.toString())
    
In Java You use this code: - 
    
Date date = new Date();
CharSequence str  = DateFormat.format("dd-MM-yyyy", date.getTime());
Log.e("Date", str.toString())