I need to format my Datetime.now() to be accepted for a SOAP request.

I can't seem to find a way to format it online. Can anyone advise? I need it to look like: 2019-05-02T21:20:29.999Z

Currently I have tried: .format(), .formatLong(), Datetime.now().format('yyyy-MM-dd\'T\'HH:mm:ss.SSSZ') which I believe is the correct way, but this displays like so: 2019-05-03T16:45:18.646-0400.

2 Answers 2


You are on the right track that you need to pass in a specific format string to Datetime.now().format(...). Notice how you escape the T in your current format:


Just do the same thing with the Z:


Note that Z is a valid argument in SimpleDateFormat:

Letter    Date or Time Component    Presentation         Examples 
...       ...                       ...                  ...
Z         Time zone                 RFC 822 time zone    -0800

See also:

  • ah I forgot to escape the Z. Thank you, you're the best!
    – Olivia
    May 3, 2019 at 20:53

Another approach

String s = JSON.serialize(Datetime.now()).replace('"','');


String s = JSON.serialize(Datetime.now()).substringBetween('"');
  • That approach is covered in the links I included, but I didn't add it here because it performs much worse. That said, this Q&A thread is probably more complete having it represented here.
    – Adrian Larson
    May 3, 2019 at 23:59
  • True. I added it because it is a convenient way to generate ISO datetimes without having to know the syntax of the ISO format. And system integrations generally use ISO formats to transfer datetimes. @AdrianLarson
    – cropredy
    May 4, 2019 at 0:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .