How can I get current date in Android?

Chatar Veer Suthar picture Chatar Veer Suthar · Dec 28, 2011 · Viewed 516.1k times · Source

I wrote the following code

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

But is asking me parameter, I want current date in string format,

like

28-Dec-2011

so that I can set over TextView,

explain a bit, if you think something is necessary, I am new to Android Development.

Answer

Paresh Mayani picture Paresh Mayani · Dec 28, 2011

You can use the SimpleDateFormat class for formatting date in your desired format.

Just check this link where you get an idea for your example.

For example:

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); 

Update:

The detailed example is here, I would suggest you go through this example and understand the concept of SimpleDateFormat class.

Final Solution:

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);