How to get month and day in android?
30,373
Solution 1
You're over-complicating the problem. If all you need is to format a date in a certain way, then use java.text.SimpleDateFormat
class. See the documentation here: http://developer.android.com/reference/java/text/SimpleDateFormat.html
If you really do need to get individual parts, then you are correct in using Calendar.get
method. I suggest you read up on java.util.Calendar
.
Solution 2
String month=c.get(Calendar.MONTH)+1+"";
if(month.length()<2){
month="0"+month;
}
Solution 3
Date date = calendar.getTime();
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
String formattedDate = format.format(date);
Solution 4
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Log.e("TEST",sdf.format(new Date()));
Solution 5
Try this to get date and time:
Calendar rightNow = Calendar.getInstance();
String y = String.valueOf(rightNow.getTime().getYear());
String ym = String.valueOf(rightNow.getTime().getMonth());
String yd = String.valueOf(rightNow.get(Calendar.DAY_OF_MONTH));
String h = String.valueOf(rightNow.getTime().getHours());
String hm = String.valueOf(rightNow.getTime().getMinutes());
String hs = String.valueOf(rightNow.getTime().getSeconds());
Author by
Gabrielle
Updated on July 23, 2020Comments
-
Gabrielle almost 4 years
I need to get month and day as :01 for January, 02 for February... and 01 for first day of month, etc... I tried this :
String dd = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get((Calendar.SECOND));
but I get something like this :
2011-8-1 12:05:20
Which is the solution of this problem? For month I think I have to add 1,right?