My Insight

Simple DateUtils Class in Java

In PHP, you can easily adjust dates — whether to move forward or backward — using a built-in function. By combining strtotime() with date(), you can format and modify dates effortlessly. Here’s a quick example:

$date = strtotime("+1 day", strtotime("2020-02-28"));
echo date("Y-m-d", $date);

Difference In Java, you need to define which Object that need to be use for an output on each function or method. But what i have created here is not only increase or decrease Date. So here is the simple code.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Date Utilization for modifying a Date format
 */

public class DateUtils {

    public static String modify(String date, int numberOfDate){

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date dateObj = null;
        try {
            dateObj = formatter.parse(date);
            Calendar c = Calendar.getInstance();
            c.setTime(dateObj);
            c.add(Calendar.DATE, numberOfDate);
            dateObj = c.getTime();
            return formatter.format(dateObj);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Date modify(Date date, int numberOfDate){
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.add(Calendar.DATE, numberOfDate);
            return c.getTime();
    }

    public static long diff(Date start, Date end){
        long diffInMillies = Math.abs(end.getTime() - start.getTime());
        return TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
    }

    public static String diffWithPad(Date start, Date end, int size){
        String format = size < 10 ? "%0" + size + "d" : "%" +size+ "d";
        return String.format(format,diff(start,end));
    }


}

So you may run the code in such way.

@Test
public void testDateModifyString() {
        String date = "2024-06-21";
        int increment = 1;
        String result = DateUtils.modify(date,increment);
        logger.info("Date Input = {}, increment = {}, Date result = {} ", date, increment, result);
}

The result is..

 Date Input = 2024-06-21, increment = 1, Date result = 2024-06-22 

More information for date in Java, you might find it here

That’s all folks! Happy coding! 🥰😍


Leave a Reply

Your email address will not be published. Required fields are marked *