Forum Moderators: coopster

Message Too Old, No Replies

Help Converting a string

         

IntegrityWebDev

9:17 pm on Mar 1, 2011 (gmt 0)

10+ Year Member



I have a function that returns a string in this format:
-5
+12
-10
+1
0
etc...

It is a gmt offset I retrieved from a site's API.

I need to convert this to the following formats before inserting into a DB into a TIME field.

-05:00:00
+12:00:00
-10:00:00
+01:00:00
00:00:00

any thoughts on this?

Thanks!
Chris

Matthew1980

9:40 pm on Mar 1, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there,

If these are held in a variable, could you just typecast them, as I think that datetime format is actually a string anyway, so theoretically you could just go: (string)$variable

If the function returns those variables, can't you just attach the output to a predefined bit like this:-

$ouptput = YourFunction();
$timeformat = ":00:00";
$output.$timeformat;
$result = (string)$output.$timeformat;

Or something like that...

See this link [php.net]

Though I could be totally wrong, long day and all! Apologies if I have misunderstood you.

Cheers,
MRb

Frank_Rizzo

9:42 pm on Mar 1, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I would suggest something like this:

$orig = '+11';

if($orig == 0) {
$converted = '00';
} else {
$converted = ($orig > 0 ? '+' : '-') . (abs($orig) < 10 ? '0' : '') . abs($orig);
}

$converted .= ':00:00';

IntegrityWebDev

9:57 pm on Mar 1, 2011 (gmt 0)

10+ Year Member



Frank, yours seems to work great! Matthew, sorry I didn't try yours, and it may but it seems not to account for the need of a leading zero if the number is 0-9.