Home > Net >  Is there a way to get Custom DateTime Pattern With TimeZone Offset as Request Param in Java?
Is there a way to get Custom DateTime Pattern With TimeZone Offset as Request Param in Java?

Time:10-12

I want to create an API that would take the startTime and endTime OffsetDateTime as Request Param with custom DateTimePattern along with TimeZone Offset value as well. I want the DateTime pattern to take value up to minutes only. Like this yyyy-MM-dd HH:mm but I don't know how to add offset information in this pattern. Below is the Controller class

public ResponseEntity<Object> getUsers(
        @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") OffsetDateTime startTime,
        @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm") OffsetDateTime endTime)

Is there a way to achieve this? The purpose of this API is to get the Data based on startTime and endTime and also handle the TimeZone as well.

CodePudding user response:

I think one way to do this is by getting the startTime and endTime by request parameter which gives it in string, format that and then cast them in your OffSetDateTime.

CodePudding user response:

// OffsetDateTime
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("MM/dd/yyyy 'at' hh:mm a xx");
print("OffsetDateTime", formatter1.format(OffsetDateTime.now()));
        
// OffsetTime
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("hh:mm a xx");
print("OffsetTime", formatter2.format(OffsetTime.now()));

static void print(String type, String result) {
    System.out.printf("%s: %s\n", type, result);
}

Your output will look like

OffsetDateTime: 10/12/2022 at 10:40 AM  0530
OffsetTime: 10:40 AM  0530

Hope it helps

  • Related