How to subtract X day from a Date object in Java?

Java 8 and later With Java 8’s date time API change, Use LocalDate LocalDate date = LocalDate.now().minusDays(300); Similarly you can have LocalDate date = someLocalDateInstance.minusDays(300); Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <–> java.time.LocalDateTime Date in = new Date(); LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault()); Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant()); Java 7 and earlier Use Calendar‘s add() … Read more

Convert java.util.Date to String

Convert a Date to a String using DateFormat#format method: String pattern = “MM/dd/yyyy HH:mm:ss”; // Create an instance of SimpleDateFormat used for formatting // the string representation of date according to the chosen pattern DateFormat df = new SimpleDateFormat(pattern); // Get the today date using Calendar object. Date today = Calendar.getInstance().getTime(); // Using DateFormat format … Read more

How to set time zone of a java.util.Date?

tl;dr …parsed … from a String … time zone is not specified … I want to set a specific time zone LocalDateTime.parse( “2018-01-23T01:23:45.123456789” ) // Parse string, lacking an offset-from-UTC and lacking a time zone, as a `LocalDateTime`. .atZone( ZoneId.of( “Africa/Tunis” ) ) // Assign the time zone for which you are certain this date-time … Read more