Created
April 9, 2020 16:00
-
-
Save chris-scientist/4cc51e6290e689d226dc030bf45b28c1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.github.chrisscientist.date; | |
import java.text.DateFormat; | |
import java.util.Calendar; | |
import java.util.Date; | |
import java.util.GregorianCalendar; | |
import java.util.Locale; | |
/** | |
* | |
* @author chris-scientist | |
*/ | |
public class WorkOnDate { | |
/** | |
* Here it's implemented for France. | |
*/ | |
private static Locale locale = new Locale("fr", "FR"); | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) { | |
// Compute dates | |
Date today = new Date(); | |
Date nextDay = buildDateFromToday(1, 0, 0); | |
Date previousDays = buildDateFromToday(-1, 0, 0); | |
Date previousDaysFor20200401 = buildDate(1, 3 /* for april */, 2020, -1, 0, 0); | |
// Show date | |
System.out.println("Previous day is " + showDateAsOfLocale(previousDays)); | |
System.out.println("Today is " + showDateAsOfLocale(today)); | |
System.out.println("Next day is " + showDateAsOfLocale(nextDay)); | |
System.out.println(""); | |
System.out.println("Previous days for 01/04/2020 is " + showDateAsOfLocale(previousDaysFor20200401)); | |
} | |
private static Date buildDateFromToday(int days, int months, int years) { | |
Date currentDate = new Date(); | |
return buildDateFromOtherDate(currentDate, days, months, years); | |
} | |
private static Date buildDate(int dayOfDate, int monthOfDate, int yearOfDate, int days, int months, int years) { | |
Calendar c = new GregorianCalendar(yearOfDate,monthOfDate,dayOfDate); | |
return buildDateFromOtherDate(c.getTime(), days, months, years); | |
} | |
private static Date buildDateFromOtherDate(Date aDate, int days, int months, int years) { | |
Calendar c = Calendar.getInstance(); | |
c.setTime(aDate); | |
c.add(Calendar.YEAR, years); | |
c.add(Calendar.MONTH, months); | |
c.add(Calendar.DATE, days); | |
return c.getTime(); | |
} | |
private static String showDateAsOfLocale(Date aDate) { | |
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); | |
return dateFormat.format(aDate); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment