Forum Moderators: coopster

Message Too Old, No Replies

using rtrim() or something else to strip off the end of a string

trimming end of a string

         

techtheatre

3:54 am on Jan 19, 2009 (gmt 0)

10+ Year Member



I have a string that is formatted like this:
20081217120000[0:GMT]

My ultimate goal is to insert it into MySQL in a date field. I assume (maybe incorrectly) that the first thing I need to do is strip off the last 13 characters so that it reads 20081217. I am then hoping that I can simply insert that as the date into MySQL and it will figure out how to treat it as a date (maybe I will not be this lucky, but I think I read somewhere that this works).

So...this is a 2 part question:

1. is there a way to use rtrim() to trim a certain NUMBER of characters from the right side...all i can find is how to trim CERTAIN characters from the right side... Is there a better way than rtrim()?

2. is there a more direct or better approach to convert my string into a usable MySQL date format (i don't care about the time portion of this string)?

DeathRay2K

4:45 am on Jan 19, 2009 (gmt 0)

10+ Year Member



For the first part, you could use substr to just get the first 8 characters, like so:
$new = substr($old, 0, 8);

As for the second part, I can't help you, sorry.

[edited by: DeathRay2K at 4:45 am (utc) on Jan. 19, 2009]

leadegroot

4:53 am on Jan 19, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You're actually quite close to the required format.
Try something like the following:

$tempdate = '20081217120000[0:GMT]';
$dateToInsert = substr($tempdate, 0, 4).'-'.substr($tempdate, 4, 2).'-'.substr($tempdate, 6, 2);

and drop that (quoted, of course) into the insert command.
(Code not tested, just written)

You could also try something like:
$dateToInsert = date('Y-m-d', strtotime($tempdate));

hope it helps :)

techtheatre

4:55 am on Jan 19, 2009 (gmt 0)

10+ Year Member



Thanks to you both. I was so stuck on rtrim() that substr() completely slipped me. THANKS!

techtheatre

4:59 am on Jan 19, 2009 (gmt 0)

10+ Year Member



Just in case anyone in the future ever reads this thread...

This works PERFECTLY:

$tempdate = '20081217120000[0:GMT]';
$dateToInsert = substr($tempdate, 0, 4).'-'.substr($tempdate, 4, 2).'-'.substr($tempdate, 6, 2);

This does not work (unfortunately):

$dateToInsert = date('Y-m-d', strtotime($tempdate));

Thanks again to you both!