简体   繁体   中英

How to print the date in dd/mm format in java

I want to write a class so that I can print the date in dd/mm format, but I have no idea to start.

Here is the main() part

Code:

import java.util.Arrays;

public class SortMonthDate {

    public static void main(String[] args) {
        MonthDate[] mdates = new MonthDate[5];
        mdates[0] = new MonthDate(22, 7);
        mdates[1] = new MonthDate(25, 8);
        mdates[2] = new MonthDate(25, 6);
        mdates[3] = new MonthDate(28, 9);
        mdates[4] = new MonthDate(5, 9);
        print(mdates);
        Arrays.sort(mdates);
        print(mdates);
    }

    static <T> void print(T[] a) {
        for (T t : a) {
            System.out.printf("%s ", t);
        }
        System.out.println();
    }
}

There's a class for that!

java.time.MonthDay

Rather than roll-your-own, use the MonthDay class built into Java 8 and later. For Java 6 & 7, use the back-port.

MonthDay[] mds = new MonthDay[5] ;
mds[0] = MonthDay.of( 7 , 22 ) ;
mds[1] = MonthDay.of( Month.AUGUST , 25 ) ;
mds[2] = MonthDay.of( Month.JUNE , 25 ) ;
mds[3] = MonthDay.of( Month.SEPTEMBER , 28 );
mds[4] = MonthDay.of( 9 , 5 ) ;
Arrays.sort(mdates);

Better to use Java Collections generally.

List< MonthDay > mds = new ArrayList<>() ;
mds.add( MonthDay.of( 7 , 22 ) ) ;
mds.add( MonthDay.of( Month.AUGUST , 25 ) ) ;
mds.add( MonthDay.of( Month.JUNE , 25 ) ) ;
mds.add( MonthDay.of( Month.SEPTEMBER , 28 ) ) ;
mds.add( MonthDay.of( 9 , 5 ) ) ;
Collections.sort( mds ) ;

Strings

I want to write a class so that I can print the date in dd/mm format,

To learn about writing the class, check out the source code in the OpenJDK project.

As for generating text representing that month-day class, simply call toString to generate a value in standard ISO 8601 format. I strongly suggest use these standard formats for logging, storing, and exchanging date-time values as text.

MonthDay.of( Month.JUNE , 25 ) )
        .toString()

--06-25

For presentation to the user, specify your desired format with DateTimeFormatter class. Search Stack Overflow for more info, as this has been covered many many times already.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM" ) ;
String output = mds.get( 0 ).format( f ) ;  // Generate string in custom format.

25/06

Dump to console.

System.out.println( "mds: " + mds ) ;
System.out.println( "mds.get( 0 ) = " +  mds.get( 0 ) + "  |  output: " + output ) ;

See this code run live at IdeOne.com .

mds: [--06-25, --07-22, --08-25, --09-05, --09-28]

mds.get( 0 ) = --06-25 | output: 25/06


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 .

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

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

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 .

If you are printing an Object to System.out Java uses the Object.toString() method to get a string representation of your Object. So you can overwrite the default toString() method by implementing it in your MonthDate class.

To format the int values you can use the String.format() method. The format %02d pads the value with a 0 if smaller than 10. To get the dd/mm format you can use %02d/%02d .

With that said your toString() method can look like this:

@Override
public String toString() {
    return String.format("%02d/%02d", this.day, this.month);
}

Using new MonthDate(12, 3) this would print:

12/03

Instead of:

MonthDate@42af3438

Assuming that your MonthDate class attributes are

private int day;
private int month;

You should always implement a toString() method for every class in java because you will be representing every object differently.

As for sorting your objects by date, you cannot use Arrays.sort() because you're not sorting numbers. You should implement your own sorting method.Here's one i recommend you:

public static void sort(MonthDate[] s) {
    int[] days = new int[s.length];
    int[] months = new int[s.length];

    for (int i = 0; i < s.length; i++) {
        days[i] = s[i].day;
        months[i] = s[i].month;
    }

    Arrays.sort(days);
    Arrays.sort(months);

    for (int i = 0; i < s.length; i++) {
        s[i].day = days[i];
        s[i].month = months[i];
    }
}

We put the days and months in 2 different arrays and sorted them using Arrays.sort() , then assigned them back to the object instance.

You can also implement this toString() method and then call it in your print() method, because you cannot print an object directly with System.out.println() .

public String toString() {
    return "" + this.day + "/" + this.month;
}

In your print() function you should use the toString() method as so:

public static <T> void print(T[] a) {
    for (T t : a) {
        System.out.println(t.toString());
    }
    System.out.println();
}

Finally, you can keep your main like that and it would sort it and print it correcty.

public static void main(String[] args) {
    MonthDate[] mdates = new MonthDate[5];
    mdates[0] = new SortMonthDate(22, 7);
    mdates[1] = new SortMonthDate(25, 8);
    mdates[2] = new SortMonthDate(25, 6);
    mdates[3] = new SortMonthDate(28, 9);
    mdates[4] = new SortMonthDate(5, 9);
    print(mdates);
    sort(mdates);
    print(mdates);
}

Here's the full code:

MonthDate class

import java.util.Arrays;

public class MonthDate {

    private int day;
    private int month;

    public MonthDate(int day, int month) {
        this.day = day;
        this.month = month;
    }

    public static void sort(MonthDate[] s) {
        int[] days = new int[s.length];
        int[] months = new int[s.length];

        for (int i = 0; i < s.length; i++) {
            days[i] = s[i].day;
            months[i] = s[i].month;
        }

        Arrays.sort(days);
        Arrays.sort(months);

        for (int i = 0; i < s.length; i++) {
            s[i].day = days[i];
            s[i].month = months[i];
        }
    }

    public String toString() {
        return "" + this.day + "/" + this.month;
    }

    public static <T> void print(T[] a) {
        for (T t : a) {
            System.out.println(t.toString());
        }
        System.out.println();
    }

}

SortMonthDate class

public class SortMonthDate {

    public static void main(String[] args) {


            MonthDate[] mdates = new MonthDate[5];
            mdates[0] = new MonthDate(22, 7);
            mdates[1] = new MonthDate(25, 8);
            mdates[2] = new MonthDate(25, 6);
            mdates[3] = new MonthDate(28, 9);
            mdates[4] = new MonthDate(5, 9);
            MonthDate.print(mdates);
            MonthDate.sort(mdates);
            MonthDate.print(mdates);

    }

}

Note that instead of making your MonthDate methods static, you could make them not static and call them in main using, for example, mdates.print(); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM