26

I am having trouble displaying the date in a double digit format. I want it to be so that when the day or the month is a single digit example: 4 It would display 04. I'm having trouble coming up with the logic for it, if somebody can help me I would be really grateful.

Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int month = c.get(Calendar.MONTH);

        if (month % 10 == 0) {

            Place = 0 + month;
        }
        String Dates = year + "-" + Place + "-" + day;
        Date.setText((Dates));
BenMorel
  • 34,448
  • 50
  • 182
  • 322
The Tokenizer
  • 1,564
  • 3
  • 29
  • 46
  • Maybe Place = "0" + month would work as it is stored then as a String? – drodil Apr 18 '12 at 06:26
  • 1
    FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. Much of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Mar 28 '18 at 19:37

12 Answers12

54
DecimalFormat mFormat= new DecimalFormat("00");
mFormat.format(Double.valueOf(year));

in your case:

 mFormat.setRoundingMode(RoundingMode.DOWN);
 String Dates =  mFormat.format(Double.valueOf(year)) + "-" +  mFormat.format(Double.valueOf(Place)) + "-" +  mFormat.format(Double.valueOf(day));
Mohammed Azharuddin Shaikh
  • 41,633
  • 14
  • 96
  • 115
  • 1
    This code is great, but for some reason it forcible displays my code as 3/18 instead of 4/18. I dont understand why – The Tokenizer Apr 18 '12 at 07:03
  • try mFormat.setRoundingMode(RoundingMode.DOWN); see edited answer. – Mohammed Azharuddin Shaikh Apr 18 '12 at 07:06
  • FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. Much of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android in the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project. See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Mar 28 '18 at 19:37
13

Please use SimpleDateFormat

SimpleDateFormat sd1 = new SimpleDateFormat("dd-MMM-yyyy");
System.out.println("Date : " + sd1.format(new Date(c.getTimeInMillis()));

Output

Date : 18-Apr-2012
Aung Thaw Aye
  • 437
  • 3
  • 7
  • 3
    @GregKopff No, not correct. The Question explicitly asked for the month as a double-digit number not a name-of-month. – Basil Bourque May 06 '16 at 18:30
  • @Basil , then, you can use dd-MM-yyyy instead of dd-MMM-yyyy – Hatim Dec 24 '16 at 05:59
  • @Hatim I suggest you edit your Answer to provide a relevant solution rather than post as a Comment. Then again maybe you shouldn't. Your irrelevant Answer has 13 up-votes and one complement while my own spot-on Answer has one down-vote. – Basil Bourque Mar 01 '17 at 22:29
  • 1
    @Basil, I just posted a comment. this is not my answer – Hatim Mar 02 '17 at 18:20
12
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH)+1;

String Dates = year + "-" +(month<10?("0"+month):(month)) + "-" + day;
Date.setText((Dates));
V.J.
  • 9,492
  • 4
  • 33
  • 49
8
if (dayOfMonth < 10) {
    NumberFormat f = new DecimalFormat("00");
    Sting date = String.valueOf(f.format(dayOfMonth));
}
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
Ness Tyagi
  • 2,008
  • 24
  • 18
5

tl;dr

LocalDate.now()
         .toString()

2016-01-07

Better to always specify your desired/expected time zone explicitly.

LocalDate.now( ZoneId.of( "America/Montreal" ) )
         .toString()

Avoid old date-time classes

The java.util.Calendar class you are using is now legacy. Avoid this class, along with java.util.Date and such. These have proven to be poorly designed, confusing, and troublesome.

java.time

The old date-time classes have been supplanted by the java.time framework built into Java 8 and later. Much of the functionality has been back-ported to Java 6 & 7 in the ThreeTen-Backport project, and further adapted to Android in ThreeTenABP.

These modern classes can accomplish your goal in a single line of code, as seen below.

Date-time formatting features

Both the old outmoded date-time classes as well as java.time classes offer formatting features. No need for you to be writing your own formatting code.

Time Zone

Time zone is crucial to determine the date. The date varies around the world by time zone as a new day dawns earlier in the east. This issue was ignored in the Question and other Answers. If omitted, the JVM’s current default time zone is implicitly applied. Better to explicitly specify your desired/expected time zone.

LocalDate

For a date-only value without time-of-day and without time zone, use the LocalDate. While no time zone is stored within the LocalDate, a time zone determines “today”.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );

ISO 8601

Your desired format of YYYY-MM-DD with double digits happens to comply with the ISO 8601 standard defining sensible formats for textual representations of date-time values. This standard is used by default in java.time classes for parsing/generating strings.

String output = today.toString();

That’s all, 3 lines of code. You could even combine them.

String output = LocalDate.now( ZoneId.of( "America/Montreal" ) ).toString();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
5

you can use String.format() method.

example :

String.format("%02d", month);

so they would add "0" in front of month if the chosen month less than 10.

5

Purely using the Java 8 Time library:

String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
Zee
  • 1,321
  • 2
  • 18
  • 41
  • Actually, the Question asks for entire date, year-month-day. – Basil Bourque Mar 28 '18 at 15:47
  • Modified my response to account for that. Although I just noticed this is tagged as android and my response was for the standard jdk. Not sure if it will differ. – Zee Mar 28 '18 at 17:56
  • Later Android has an implementation of *java.time*. For earlier Android, use the *ThreeTen-Backport* and *ThreeTenABP* projects. – Basil Bourque Mar 28 '18 at 18:41
  • No need to specify that formatting pattern. That format year-month-day is standard ISO 8601 format used by default in the `toString` as explained in [my Answer](https://stackoverflow.com/a/37079498/642706) posted a couple years ago. – Basil Bourque Mar 28 '18 at 18:45
3
if ((month+1)<10){
    place = "0"+(String) (month+1)
}

do the same for day and you are good to go.

+1 in month because it starts with 0.

drulabs
  • 3,071
  • 28
  • 35
2

Use SimpleDateFormat class.. There are a lot of ways to do it..

something like this..

 SimpleDateFormat sdfSource = new SimpleDateFormat("dd/MM/yy"); // you can add any format..


      Date date = sdfSource.parse(strDate);
ngesh
  • 13,398
  • 4
  • 44
  • 60
  • This is far more convenient than the accepted answer – WestCoastProjects Jan 30 '18 at 06:44
  • @javadba Actually, this Answer uses confusing troublesome old date-time classes that are now supplanted by the *java.time* classes. For earlier Android, see the *ThreeTen-Backport* and *ThreeTenABP* projects. – Basil Bourque Mar 28 '18 at 18:51
2

You can use SimpleDateFormat class

String dates = new java.text.SimpleDateFormat("dd-MM-YYYY").format(new Date())

for more information https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

srsajid
  • 1,717
  • 15
  • 12
0

Joda-Time

Using the Joda-Time library, specifically the org.joda.time.DateTime class.

DateTime datetime = new DateTime(new Date());
String month = datetime.toString("MM");

result will be 2 digits

If you need for example a year you can use:

String year = datetime.toString("YYYY");

result will be 4 digits of the year.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Lucas Pires
  • 1,281
  • 14
  • 21
  • There is no `DateTime` class in Java 8. And not much Java 8 in Android. – Basil Bourque Mar 01 '17 at 22:24
  • Tks, I changed my text to org.joda.time.DateTime. – Lucas Pires Mar 02 '17 at 12:11
  • What is the problem with this answer? I already use this in differents context and I never got a problem. – Lucas Pires Jun 09 '17 at 15:30
  • Nothing wrong now. I imagine the down vote was from before you identified the Joda-Time library as the source of your classes. – Basil Bourque Jun 09 '17 at 16:02
  • FYI, the *Joda-Time* project is now in maintenance mode. The team advises migration to the java.time classes. Much of the java.time functionality is back-ported to Java 6 & 7 in the *ThreeTen-Backport* project, and further adapted to Android in the *ThreeTenABP* project. – Basil Bourque Jun 09 '17 at 16:05
  • That's was not fair. This answer responds exactly the purpose of the question. but its ok! – Lucas Pires Jun 09 '17 at 19:13
0
binding.datePicker.setOnClickListener {

            val mCurrentDate: Calendar = Calendar.getInstance()
            val mYear: Int = mCurrentDate.get(Calendar.YEAR)
            val mMonth: Int = mCurrentDate.get(Calendar.MONTH)
            val mDay: Int = mCurrentDate.get(Calendar.DAY_OF_MONTH)

            val mDatePicker = DatePickerDialog(
                requireActivity(), R.style.DialogTheme,
                { datepicker, selectedyear, selectedmonth, selectedday ->
                    val selectedmonth = selectedmonth + 1

                    val mFormat = DecimalFormat("00")
                    mFormat.roundingMode = RoundingMode.DOWN
                    val date: String =
                        mFormat.format((selectedyear)) + "-" + mFormat.format((selectedmonth)
                        ) + "-" + mFormat.format((selectedday))

                    binding.edtDob.setText(date)

                }, mYear - 18, mMonth, mDay - 1
            )
            // set maximum date to be selected as today
            // age more then 18+
            mCurrentDate.add(Calendar.YEAR, -18);
            mCurrentDate.add(Calendar.DAY_OF_MONTH, -1)
            mDatePicker.datePicker.maxDate = mCurrentDate.timeInMillis
            mDatePicker.show()
            
        }

However, you only require this part.

 val mFormat = DecimalFormat("00")
 mFormat.roundingMode = RoundingMode.DOWN
 val date: String = mFormat.format((selectedyear)) + "-" + mFormat.format((selectedmonth)) + "-" + mFormat.format((selectedday))
  binding.edtDob.setText(date)
Maruf Alam
  • 228
  • 4
  • 10