Search code examples
androiddatesimpledateformatandroid-date

How can I get current date in Android?


I wrote the following code

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

I want the current date in string format, like

28-Dec-2011

so that I can set it into a TextView.


Solution

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