Archie
Archie

Reputation: 6854

Format current date and time at UTC in Apache Camel

I am implementing integration with external service which requires current date and time. The documentation of the service says that it accepts the datetime in ISO 8601 format, but that's only partially true – it doesn't support timezone offset.

When I try ${date:now:yyyy-MM-dd'T'HH:mm:ssZ} in Camel, I get 2017-08-16T21:45:10+0200, which is not acceptable by the service.

Is there a way to make Camel date format output current date in UTC? I would like to get 2017-08-16T19:45:10Z instead of 2017-08-16T21:45:10+0200.

I would like to avoid writing separate bean for that, so I prefer solution implemented purely in XML DSL.

Upvotes: 7

Views: 15247

Answers (2)

user272735
user272735

Reputation: 10648

Camel Simple language has date-with-timezone variable that can be used to query time of different time zones like:

${date-with-timezone:now:CET:yyyy-MM-dd'T'HH:mm:ss}
${date-with-timezone:now:UTC:yyyy-MM-dd'T'HH:mm:ss}
${date-with-timezone:now:EST:yyyy-MM-dd'T'HH:mm:ss}

That would become:

2022-03-22T16:08:43 // CET is UTC+1
2022-03-22T15:08:43 // UTC
2022-03-22T10:08:43 // EST is UTC-5

The last parameter is java.text.SimpleDateFormat pattern that you can use to get whatever time zone designator you would like to have. E.g.

${date-with-timezone:now:UTC:yyyy-MM-dd'T'HH:mm:ssX}

Gives you:

2022-03-22T15:08:43Z

Upvotes: 7

Archie
Archie

Reputation: 6854

I've managed to come up with a solution using Groovy expression:

<groovy>
  java.time.ZonedDateTime.now(java.time.ZoneOffset.UTC)
      .format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX"))
</groovy>

Upvotes: 6

Related Questions