How can I get current date in Android?

2019-01-04 18:48发布

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.

21条回答
姐就是有狂的资本
2楼-- · 2019-01-04 19:16
  public static String getDateTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return simpleDateFormat.format(date);
    }
查看更多
Luminary・发光体
3楼-- · 2019-01-04 19:18

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 and 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");
String formattedDate = df.format(c);
查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-04 19:18

This is the code I used:

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);
查看更多
一纸荒年 Trace。
5楼-- · 2019-01-04 19:20

Its simple one line code for get current Date in this yyyy-MM-dd format you can use your format that you want :

String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
查看更多
Animai°情兽
6楼-- · 2019-01-04 19:20

The below code displays the both time and date

Calendar cal = Calendar.getInstance();
cal.getTime().toString();
查看更多
Explosion°爆炸
7楼-- · 2019-01-04 19:20

This is the code i used:

             Date date = new Date();  // to get the date
             SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); // getting date in this format
             String formattedDate = df.format(date.getTime());
             text.setText(formattedDate);
查看更多
登录 后发表回答