Format LocalDate to String or int with Month and Day in double digit
Let’s say you wanted to format LocalDate like yyyyMMdd with date’s month and day values in double digit to String or int, then follow this tutorial.
Example 1 LocalDate to String
The below example shows how to format LocalDate to String with month and day in double digit.
package com.plan.app; import java.text.DecimalFormat; import java.time.LocalDate; public class DateFormatExample { public static void main (String[] args) { LocalDate dateNow = LocalDate.now(); System.out.println("Local Date now() : " + dateNow); System.out.println("Format date's month and day in double digit : " + getFormattedDateLocal(dateNow)); } public static String getFormattedDateLocal(LocalDate dateLocal) { DecimalFormat dmFormat= new DecimalFormat("00"); String mVal = dmFormat.format(Double.valueOf(dateLocal.getMonthValue())); String dVal = dmFormat.format(Double.valueOf(dateLocal.getDayOfMonth())); String yVal = String.valueOf(dateLocal.getYear()); String fDateLocalStr = yVal+mVal+dVal; return fDateLocalStr; } }
Output
Local Date now() : 2020-01-30 Format date's month and day in double digit : 20200130
Example 2 LocalDate to int
The below example shows how to format LocalDate to int with month and day in double digit. So that this conversion technique would help you to compare two dates easily.
package com.plan.app; import java.text.DecimalFormat; import java.time.LocalDate; public class DateFormatExample { public static void main (String[] args) { LocalDate dateNow = LocalDate.now(); System.out.println("Local Date now() : " + dateNow); System.out.println("Format date's month and day in double digit : " + getFormattedDateLocal(dateNow)); LocalDate pastDate = dateNow.minusDays(10); System.out.println("Is pastDate less than dateNow ? : " + compareDates(dateNow, pastDate)); } private static boolean compareDates(LocalDate dateNow, LocalDate pastDate) { if (getFormattedDateLocal(pastDate) < getFormattedDateLocal(dateNow)) { return true; } return false; } public static int getFormattedDateLocal(LocalDate dateLocal) { DecimalFormat dmFormat= new DecimalFormat("00"); String mVal = dmFormat.format(Double.valueOf(dateLocal.getMonthValue())); String dVal = dmFormat.format(Double.valueOf(dateLocal.getDayOfMonth())); String yVal = String.valueOf(dateLocal.getYear()); String fDateLocalStr = yVal+mVal+dVal; return Integer.parseInt(fDateLocalStr); } }
Output
Local Date now() : 2020-01-30 Format date's month and day in double digit : 20200130 Local Date minus 10 days : 2020-01-20 Is pastDate less than dateNow ? : true
Further Reading
- ZonedDateTime to LocalDateTime with a timezone
- Convert epoch milliseconds value to ZonedDateTime
- MongoDB equivalent command for SQL’s between numbers, text or dates
- Where the Docker images are stored locally?