[SalesForce] Convert string time to datetime with timezone

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:

  1. Retrieve a String that represents time in PST timezone
  2. Convert that time to PST DateTime
  3. Find the GMT representation of the PST DateTime

In order to convert the String that represents time in PST, you need to create a DateTime instance in GMT and then use the format() method to convert to PST.

Datetime pstDateTime = Datetime.valueOf(Datetime.newInstanceGMT(System.today(), <Time>).format('yyyy-MM-dd HH:mm:ss', 'PST'));

Once you have the pstDateTime, you can then create another instance of DateTime for GMT by manually constructing this instance using the pstDateTime attributes.

Datetime gmtDateTime = Datetime.newInstanceGMT(pstDateTime.year(), pstDateTime.month(), pstDateTime.day(), pstDateTime.hour(), pstDateTime.minute(), pstDateTime.second());

Using the code you have provided in your question and my code to resolve your issue, the following should work.

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);

Datetime pstDateTime = Datetime.valueOf(Datetime.newInstanceGMT(System.today(), <Time>).format('yyyy-MM-dd HH:mm:ss', 'PST'));

Datetime gmtDateTime = Datetime.newInstanceGMT(pstDateTime.year(), pstDateTime.month(), pstDateTime.day(), pstDateTime.hour(), pstDateTime.minute(), pstDateTime.second());
Related Topic