How to form date and time in Java - java

I'm using LocalDateTime.now() and OffSetDateTime.now() to retrieve the date and time but it's not the desired format.
Does anyone know how to format this format? "2022-05-20T11:22:10"
I'm using MapStruct to do request and response conversions:
#Mapper
public interface ParesMapper {
ParesMapper INSTANCE = Mappers.getMapper(ParesMapper.class);
#Mapping(target = "data", source = "data")
DataParesResponse toResponse(DataPares domain);
#Mapping(target = "data", source = "data")
List<DataParesResponse> toResponseList(List<DataPares> domain);
DataPares toDomain(DataParesRequest dto);
default OffsetDateTime map(LocalDateTime value) {
return OffsetDateTime.now();
}
default LocalDateTime map(OffsetDateTime value) {
return LocalDateTime.now();
}
}
I look forward to helping you find a solution.

You can use DateTimeFormatter method
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class DateTimeFormatter {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
}
}

Related

How to format the date time correctly in Spring Boot?

I would like to know how to format the date time correctly? The result is Localdatetime yyyy-MM-ddTHH:mm.
Could you advise how to solve?
I'm using Java 11, and does it because #JsonFormat not support #RequestParam?
Controller:
#PostMapping("/checkFollowupDate")
public LocalDateTime updateCaseFollowup(#RequestParam("followupDate") #DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS") LocalDateTime followupDate) {
return followupDate;
}
Entity:
#Entity
#Table(name = "caseFollowup")
public class CaseFollowup {
#JsonFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS")
private LocalDateTime followupDate;
Since you are using Spring-boot , I'm also assuming you are using java8 . In any case try using java8 time api for date like :
#JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime followupDate;
and if you are on JPA 2.1 which was released before java8 then in your entity class you could have a converter to convert it for sql timestamp like :
#Converter(autoApply = true)
public class LocalDateTimeAttributeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
#Override
public Timestamp convertToDatabaseColumn(LocalDateTime locDateTime) {
return locDateTime == null ? null : Timestamp.valueOf(locDateTime);
}
#Override
public LocalDateTime convertToEntityAttribute(Timestamp sqlTimestamp) {
return sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime();
}
}
Remember that in newer version of Hibernate(Hibernate 5) and JPA the above conversion will be performed automatically and doesn't require you to provide the above method.
If your requirement is just to persist the Date read from the #RequestParam through the entity class in a particular format, you could always convert it manually into any format that you may choose before setting the value into your entity class like :
#PostMapping("/caseFollowup")
public Integer updateCaseFollowup(#RequestParam("followupDate")
LocalDateTime followupDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatDateTime = followupDate.format(formatter);
}
use this code in you model class :
#JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssZ", shape = JsonFormat.Shape.STRING)
private OffsetDateTime lastModifiedDate;
and create this class mapper :
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
#Component
public class DateMapper {
public OffsetDateTime asOffsetDateTime(Timestamp ts){
if (ts != null){
return OffsetDateTime.of(ts.toLocalDateTime().getYear(), ts.toLocalDateTime().getMonthValue(),
ts.toLocalDateTime().getDayOfMonth(), ts.toLocalDateTime().getHour(), ts.toLocalDateTime().getMinute(),
ts.toLocalDateTime().getSecond(), ts.toLocalDateTime().getNano(), ZoneOffset.UTC);
} else {
return null;
}
}
public Timestamp asTimestamp(OffsetDateTime offsetDateTime){
if(offsetDateTime != null) {
return Timestamp.valueOf(offsetDateTime.atZoneSameInstant(ZoneOffset.UTC).toLocalDateTime());
} else {
return null;
}
}
}

Hibernate - Override output format of date when generating JSON

With a temporal in my entity defined like:
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "start_time", length = 19, nullable = false)
public Date getStartTime() {
return this.startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
And marshaling JSON out put like this (simplified):
#GET
#RestSecure
#Path("/list")
#Produces(MediaType.APPLICATION_JSON)
public Response list(){
return Response.status(Response.Status.OK).entity(myEntityList).build();
}
Is there a simple way of overriding output date format?
What I am getting out is the epoch like this:
"startTime": 1582261711000,
What I need is the date in ISO 8601 format like this:
"startTime": "2020-02-21T05:08:31Z",
You can use jackson's DateFormat annotation:
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssZ")

Format date in response JSON from controller

I am returning a JSON as a response from the controller. I want to format the date fields in this response.
Controller-
#RequestMapping(value = "/call", method = RequestMethod.GET)
public SampleDTO get()
{
......
return sampleDTO;
}
SampleDTO-
{
"date" : "2020-03-10T08:57:58+0000",
"text" : "abc"
}
I want to format the date field to dd-MM-yyyy
To do this I add the #JsonFormat annotation to the bean class of SampleDTO.
SampleDTO.java -
import java.util.Date;
public class SampleDTO
{
#JsonFormat(pattern = "dd-MM-yyyy")
private Date date;
private String text;
#JsonFormat(pattern = "dd-MM-yyyy")
public void setDate(final Date date)
{
this.date = date;
}
#JsonFormat(pattern = "dd-MM-yyyy")
public Date getDate()
{
return date;
}
public void setText(final String text)
{
this.text = text;
}
public String getText()
{
return text;
}
}
Still, I am getting this format in the response on my browser.
"date" : "2020-03-10T08:57:58+0000"
EDIT 1:
Instead of returning the sampleDTO, converting it to String directly in the code works perfectly fine.
This works like a charm:
SampleDTO sampleDTO = new SampleDTO();
sampleDTO.setCreated(new Date());
ObjectMapper om = new ObjectMapper();
return om.writeValueAsString(sampleDTO);
Please, check that your Date is from java.util and not from java.sql package. Plus try the following:
#JsonSerialize(as = Date.class)
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="dd-MM-yyyy")
Could you try this on the field level and remove from getDate() method in your DTO.
Something like this,
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private Date date;
This should work with your current version of jackson-databind:2.9.8.jar.
Here is the small example for you:
public class ExampleMain {
public static void main(String[] args) throws IOException {
Employee employee = new Employee();
employee.setDateOfBirth(Date.from(ZonedDateTime.now().minusYears(30).toInstant()));
System.out.println("-- before serialization --");
System.out.println(employee);
System.out.println("-- after serialization --");
ObjectMapper om = new ObjectMapper();
String jsonString = om.writeValueAsString(employee);
System.out.println(jsonString);
System.out.println("-- after deserialization --");
System.out.println(om.readValue(jsonString, Employee.class));
}
}
public class Employee {
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
private Date dateOfBirth;
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
#Override
public String toString() {
return "Employee{" +
", dateOfBirth=" + dateOfBirth +
'}';
}
}
There are three levels of how you can solve this date format issue with Spring.
1) Using #JsonFormat on your date fields
In this case, you need to use the same annotation in front of all your private date members.
public class MyBean{
#JsonFormat(pattern="yyyy-MM-dd")
private Date birthday;
#JsonFormat(pattern="yyyy-MM-dd")
private LocalDate birthday;
// getters and setters here
}
2) Setting the Default format
If you want to configure the default date format for all dates in your application, add the following line to the application.properties or application.yml config file:
spring.jackson.date-format=yyyy-MM-dd
Unfortunately, this solution doesn't work with the Java 8 date types, like LocalDate and LocalDateTime.
3) Customizing your Jackson ObjectMapper
This solution works like a charm with Java 8 date types as well.
#Configuration
public class ContactAppConfig {
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
#Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return builder -> {
builder.simpleDateFormat(DATE_TIME_FORMAT);
builder.serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
builder.serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
};
}
}
I suggest you use the 3rd option.
you can use jstl format to format the date :)
<%# taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<fmt:formatDate pattern = "yyyy-MM-dd" value = "${date}" />

Problem with formatting LocalDateTime with org.json library

I have a problem with the serialization of an object to JSON using the org.json library.
In my code I have:
String resultStr = new JSONObject(result).toString();
and in result object two fields of type LocalDateTime:
private LocalDateTime startDate;
private LocalDateTime stopDate;
In variable resultStr I got date in following format:
2020-01-23T14:13:30.121205
I want this ISO format:
2016-07-14T07:58:08.158Z
I know that in Jackson there is an annotation #JsonFormat, but I didn't find anything like that in org.json. How to define a format of LocalDateTime in JSON string with org.json?
In JSON in Java, it seems that there are not much support for Date/Time formatting.
To customize the formatting of LocalDateTime field, we can make use of
1. #JSONPropertyIgnore to ignore the original getter to be serialized
2. #JSONPropertyName to annotate a new getter with ignored field name, which return the desired formatted date string, as following:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.json.JSONObject;
import org.json.JSONPropertyIgnore;
import org.json.JSONPropertyName;
public class CustomizeLocalDateTimeFormatInOrgJson {
public static void main(String[] args) {
Result result = new Result(LocalDateTime.now(), LocalDateTime.now());
String resultStr = new JSONObject(result).toString();
System.out.println(resultStr);
}
public static class Result {
DateTimeFormatter customDateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssS'Z'");
private LocalDateTime startDate;
#JSONPropertyIgnore
public LocalDateTime getStartDate() {
return startDate;
}
#JSONPropertyName("startDate")
public String getStartDateString() {
return customDateTimeFormat.format(startDate);
}
private LocalDateTime stopDate;
#JSONPropertyIgnore
public LocalDateTime getStopDate() {
return stopDate;
}
#JSONPropertyName("stopDate")
public String getStopDateString() {
return customDateTimeFormat.format(stopDate);
}
public void setStopDate(LocalDateTime stopDate) {
this.stopDate = stopDate;
}
public void setStartDate(LocalDateTime startDate) {
this.startDate = startDate;
}
public Result(LocalDateTime startDate, LocalDateTime stopDate) {
super();
this.startDate = startDate;
this.stopDate = stopDate;
}
}
}

Jackson #JsonFormat converting date with incorrect timezone

I have a value coming in from JSON payload as:
"callStartTime" : "2019-03-27 13:00:00"
Entity.java
#JsonProperty("callStartTime")
#Column(name = "call_start_dt", nullable = false)
#JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE)
private Date callStartTime;
When I printed it on console, it says:
Wed Mar 27 08:00:00 CDT 2019
I wanted to be the same as it was in json payload. How I can fix it?
I am just taking date from json and writing it to mysql db in a datetime column.
Simple solution: I solved it by changing the data type to String which completes my aim to capture the value as it is coming from JSON payload. Using Date and other data types were converting the value to some different timezone.
#JsonProperty("callStartTime")
#Column(name = "call_start_dt", nullable = false)
#JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE)
private **String** callStartTime;
Try this
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
private Date callStartTime;
java.util.Date does not capture time zone data. It only knows about number of millis since the epoch.
You could try using one of the modules in jackson-modules-java8 and deserialize into an instance of ZonedDateTime instead, which is time-zone aware.
EDIT: try this as a basis for getting it to work:
public class SoTest {
public static void main(String[] args) throws Exception {
ObjectMapper om = new ObjectMapper().registerModule(new ParameterNamesModule())
.registerModule(new JavaTimeModule());
String s = "{\"callStartTime\" : \"2019-03-27T13:00:00Z\" }";
MyType mt = om.readValue(s, MyType.class);
System.out.println(mt.getCallStartTime());
}
}
class MyType {
#JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssX", lenient = OptBoolean.FALSE)
private ZonedDateTime callStartTime;
public ZonedDateTime getCallStartTime() {
return callStartTime;
}
public void setCallStartTime(ZonedDateTime date) {
this.callStartTime = date;
}
}
There are two possible solutions for this :
1. Define ObjectMapper bean and set date format.
#Bean
public ObjectMapper objectMapper()
{
ObjectMapper objectMapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
objectMapper.setDateFormat(df);
return objectMapper;
}
2. Set date format for the particular field using #JsonFormat
#JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", lenient = OptBoolean.FALSE)
private Date createTime;

Categories

Resources