0

I have below apex code.

Datetime myCSTTimeNow      = Datetime.now().format('yyyy-MM-dd HH:mm:ss','America/Chicago');
Datetime rightNowAsCST     = Datetime.valueOfGmt(myCSTTimeNow);
Integer currentCSThour     = integer.valueOf(rightNowAsCST.format('hh'));
Integer currentCSTminutes  = integer.valueOf(rightNowAsCST.format('mm'));
Time currentTime           = Time.newInstance(currentCSThour, currentCSThour, 00, 00);
String currentDayOfTheWeek = rightNowAsCST.format('EEEE');


System.debug('rightNowAsCST '+ rightNowAsCST);
System.debug('current time split '+ string.valueOf(rightNowAsCST).split(' '));
System.debug('currentCSThour '+ currentCSThour);
System.debug('currentCSTminutes '+ currentCSTminutes);
System.debug('currentTime '+ currentTime);

below is the output of the above code

enter image description here

I have also tried changing

Integer currentCSThour     = integer.valueOf(rightNowAsCST.format('hh'));

to

Integer currentCSThour     = integer.valueOf(rightNowAsCST.format('hh','America/Chicago'));

but I still get the output as 2 instead of 7.

I am getting the expected value when I print rightNowAsCST it converts my time with CST time but when I use format or even use split to fetch the time then it changes the time value (7:22 with 2:22)and because of the incorrect time it prints incorrect day also. I would highly appreciate it if someone helps me to understand this sorcery!

1

@gs650x : Please note that format() method

Converts the date to the local time zone and returns the converted date as a formatted string using the locale of the context user. If the time zone cannot be determined, GMT is used.

I hope your expectations is you need hour value for any Timezone, If so you directly use

String x = DateTime.Now(timeFormat,TimeZoneSidKey);

Then you can split it

You can use below piece of code

Datetime myNowGMTTime = DateTime.Now();
System.debug('myNowGMTTime--->'+myNowGMTTime);
//But if i Use format it will show my current TimeZone time
String myTimeWithMyTimeZone = DateTime.now().format();
System.debug('myTimeWithMyTimeZone--->'+myTimeWithMyTimeZone);


/* NOW COMING TO YOUR QUESTION  , IF YOUR EXPECTATIONS IS YOU NEED HOUR VALUE FOR A PARTICULAR TIMEZONE 
   BELOW IS THE CODE ----------------*/
String americaChicagoTime =Datetime.now().format('yyyy-MM-dd HH:mm:ss','America/Chicago');
System.debug('americaChicagoTime--->'+americaChicagoTime);

String americaChicagoTimeHour=americaChicagoTime.split(' ')[1].split(':')[0];
System.debug('americaChicagoTimeHour--->'+americaChicagoTimeHour);

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.