Convert Datetime to string in GMT format?

String formatedDt = dt.format('yyyy-MM-dd'T'HH:mm:ss'Z'');

I want to used this string in dyamic SOQL but it gives me formatted string in localtimezone, can anyone help me how do i get it in GTM ?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Use DateTime’s formatGMT to format the time according to your specs in GMT.

String formatedDt = dt.formatGMT('yyyy-MM-dd'T'HH:mm:ss'Z'');

Method 2

you can use the dateGMT() method:


Return the Date component of a Datetime in the GMT time zone.

public Date dateGMT()

Return Value

Type: Date


DateTime myDateTime = DateTime.newInstance(2006, 3, 16, 23, 0, 0);
Date myDate = myDateTime.dateGMT();
Date expected = Date.newInstance(2006, 3, 17);
System.assertEquals(expected, myDate);

from the Apex developer Guide

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x