Java util date to String Conversion
In this tutorial will see how to convert date object to string objects in java. To convert it, there are few ways to implement it. Using java.util.Date and Using java 8 time and date APIs.
Let’s see how to convert date to string in java
java.util.Date to String
First, we need to define the pattern we need to convert it to.
package com.slb.core.java;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DateFormatter {
private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a";
private static final String EXPECTED_DATE_STRING_FORMAT = "Mar 1, 2018 12:00 PM";
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("IST"));
Calendar calendar = Calendar.getInstance();
calendar.set(2018, Calendar.MARCH, 1, 12, 0);
Date date = calendar.getTime();
DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
String formattedDate = formatter.format(date);
assertEquals(EXPECTED_DATE_STRING_FORMAT , formattedDate);
System.out.println(formattedDate);
}
}
In the above code snippet, we are using simpleDateFormatter to format the date.
O/P
Mar 1, 2018 12:00 PM
Process finished with exit code 0
Converting Using Java 8 Date/Time API
Let’s see how to convert string to java util date in java 8. We will make java 8’s date and time API to format the date. Checkout JAVA8 tutorials here.
package com.slb.core.java;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DateFormatter {
private static final String DATE_FORMAT = "MMM d, yyyy HH:mm a";
private static final String EXPECTED_DATE_STRING_FORMAT = "Mar 1, 2023 12:00 PM";
public static void main(String[] args) {
TimeZone.setDefault(TimeZone.getTimeZone("IST"));
Calendar calendar = Calendar.getInstance();
calendar.set(2023, Calendar.MARCH, 1, 12, 0);
Date date = calendar.getTime();
DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
String formattedDate = formatter.format(date);
assertEquals(EXPECTED_DATE_STRING_FORMAT , formattedDate);
System.out.println(formattedDate);
//using java 8
DateTimeFormatter formatterJava8Example = DateTimeFormatter.ofPattern(DATE_FORMAT);
Instant instant = date.toInstant();
LocalDateTime localDateTime = instant.atZone(ZoneId.of("UTC"))
.toLocalDateTime();
String formattedDateJava8 = localDateTime.format(formatterJava8Example);
System.out.println(formattedDateJava8);
}
}
O/P
Mar 1, 2023 12:00 PM
Mar 1, 2023 06:30 AM
Process finished with exit code 0
Checkout the complete example here at githib@SLB