I have a requirement where I want to convert a String time "15:00" (pstTime String) in PST timezone to a string time "08:00"(gmtTime String) in GMT. The date is immaterial.
The way I'm trying to achieve this is by creating a PST Datetime from the 'pstTime String' and then getting the GMT Datetime from it to get the time component.
The problem is that I'm not able to create a PST Datetime from the 'PstTime string.
I have tried creating a Datetime with newInstance which returns the Datetime in GMT format. However, this time is a PST time so the GMT value is not correct. Even if I convert this to a PST timezone with offset, this will not show the correct result since I'm not able to set it in PST timezone.
String timeStr = "15:00";
String defaultTime = '00:00';
String[] ct = (timeStr != null) ? timeStr.split(':') :
defaultTime.split(':');
Time t = time.newInstance(Integer.valueOf(ct[0]), Integer.valueOf(ct[1]), 0, 0);
//dummy date creation to get time
Datetime dt = Datetime.newInstanceGmt(System.today(), t);
Output of this is – 2018-08-16 15:00:00
How can I achieve something like this? Is it doable?
Best Answer
So, it sounds like you are trying to do the following:
String
that represents time in PST timezoneDateTime
In order to convert the
String
that represents time in PST, you need to create aDateTime
instance in GMT and then use theformat()
method to convert to PST.Once you have the
pstDateTime
, you can then create another instance ofDateTime
for GMT by manually constructing this instance using thepstDateTime
attributes.Using the code you have provided in your question and my code to resolve your issue, the following should work.