A quick list of Java Codes I use for Date & String Manipulation

A quick list of Java Codes I use for Date & String Manipulation

I spent most of my web development career working on JavaScript. I usually use battle tested third party libraries such as Lodash for utilities and LuxonJS for date/time manipulation. This is to avoid reinventing the wheel.

Working in one of the latest Automation projects written in Java, a programming language that I've used a lot during my University years, here is a list of codes that I use for manipulating dates and string in general.

What I like with Java is, by default using built in libraries such as java.utils, you get lots of utilities. Moreover, with Maven, it's easy to install third party libraries.

Convert date to Local Date

localDateLocalDate localSelectedDate = newDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

Difference between two months

ChronoUnit.MONTHS.between(dateNow.withDayOfMonth(1),anotherDate.withDayOfMonth(1));

You can similarly calculate the difference between days, hours or other similar units.

Next/Previous Month

String nextMonth = StringUtils.capitalize(selectedDate.plusMonths(1).getMonth().name().toLowerCase());
String previousMonth = StringUtils.capitalize(selectedDate.minusMonths(1).getMonth().name().toLowerCase());

Switch Dates formats

SimpleDateFormat supportedFormat = new SimpleDateFormat("dd/MM", Locale.ENGLISH);
return supportedFormat.format(date);

How to get an element in array with a property containing part of a text?

No more use of for / for each loops.

array.stream().filter(el -> el.getProperty().contains("this text")).toArray();

Streams can be used as from Java 8.

How to compare two strings with different cases?

This is not related to a specific programming language.

One way is to first transform both strings into lowercase then do the comparison. A better way is to compare and ignore the case.

if (element.getText().equalsIgnoreCase(property.GetDescription())) {
	element.click();
}