is there a way to convert a java.util.Date to format

dd/mm/yyyy HH:mm:ss ?

Dani AI

Generated

A quick correction and a fuller answer: was on the right track but the correct class name is java.text.SimpleDateFormat (not SimpleDateFormatter). For the layout you asked for use the pattern dd/MM/yyyy HH:mm:ss (note uppercase M for month — lowercase m means minutes).

Example with the legacy API (pre‑Java 8):

Date now = new Date();
SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String formatted = fmt.format(now);
Date parsed = fmt.parse("31/12/2020 23:59:59");

Caveats: SimpleDateFormat is not thread‑safe — do not reuse a single instance across threads unless you synchronize or use ThreadLocal. Also set fmt.setLenient(false) if you need strict parsing.

Modern recommendation (Java 8+): prefer the java.time API which is thread‑safe and clearer:

LocalDateTime now = LocalDateTime.now();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
String formatted = now.format(fmt);

LocalDateTime parsed = LocalDateTime.parse("31/12/2020 23:59:59", fmt);

To convert between java.util.Date and the new API:

LocalDateTime ldt = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
Date legacy = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Quick gotchas: use HH for 24‑hour clock (hh + a for 12‑hour), MM for month (not mm), and prefer yyyy (calendar year) over YYYY (week year) unless you know you need week‑year semantics.

Recommended Answers

All 2 Replies

Check the class:
java.text.SimpleDateFormatter

thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.