How to convert only the date without time to a string in Java

1 Answer

0 votes
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
    Function: dateToString
    Purpose : Convert a LocalDate to a string (YYYY-MM-DD)
*/
public class Main {

    public static String dateToString(LocalDate date) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return date.format(fmt);
    }

    // Build a LocalDate from integers
    public static LocalDate makeDate(int y, int m, int d) {
        return LocalDate.of(y, m, d);
    }

    public static void main(String[] args) {

        // Today's date
        LocalDate today = LocalDate.now();
        System.out.println("Today's date is: " + dateToString(today));

        // Hard‑coded date
        LocalDate myDate = makeDate(2025, 12, 7);
        System.out.println("Hard-coded date is: " + dateToString(myDate));
    }
}



/*
run:

Today's date is: 2026-05-30
Hard-coded date is: 2025-12-07

*/

 



answered 9 hours ago by avibootz

Related questions

...