Android studio - Textview show date

Ivan picture Ivan · Oct 28, 2016 · Viewed 14.9k times · Source

I've read a lot of posts about this, but I cannot get it to work. I need a textView (id - datumprikaz ) to show the current date like this: 28.11.2016.

I've managed to add the date using this method in my java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView dateView = (TextView)findViewById(R.id.datumprikaz);
    setDate(dateView);

}

public void setDate (TextView view){
    String str = String.format("%tc", new Date());
    view.setText(str);
}

The problem is I get as a result: Fri Oct 28 19:57:37 GMT

And I just need it to show the current date like 28.11.2016.

How do I do this ?

I've tried another method with

    String trenutniDatum = DateFormat.getDateTimeInstance().format(new Date());
    datumprikaz textView = (datumprikaz) findViewById(R.id.datumprikaz);
    datumprikaz.setText(trenutniDatum);

But the setText is red and won't work.

How do I get this ? 28.11.2016 in a textView with the id datumprikaz

Answer

Real73 picture Real73 · Oct 28, 2016

what you need is just customizing you date.Here is simple solution for your setDate method.

public void setDate (TextView view){

    Date today = Calendar.getInstance().getTime();//getting date
    SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");//formating according to my need
    String date = formatter.format(today);
    view.setText(date);
}

you can format a date in many, many different ways. Here are some of the most common custom date formats.

yyyy-MM-dd results in 2009-09-06

yyyyMMdd results in 20090906

EEE MMM dd hh:mm:ss yyyy results in Sun Sep 06 08:32:51 2009

Hope this will help.