Rahul TS
Rahul TS

Reputation: 1218

remove time stamp from string

can anyone get me a code for hiding the time stamp from a string. I used this code to get the date from the string suppose the

$date_string = "02/06/2011 11:00 am - 2:00 pm";

$date = strtotime($date_string);
$date = date('m/d/y', $date);

But the out put I am getting is something like this

 1/1/70

Please suggest a better way that I could implement for this to work I want it to show like

02/06/2011

Upvotes: 3

Views: 14484

Answers (5)

Kanchan
Kanchan

Reputation: 1619

If your string is already is date .

$date = substr($records[$datetime, 0, 10);

Upvotes: 0

Brendan Bullen
Brendan Bullen

Reputation: 11798

If the date you're looking for is already in the string and all you want to do is remove the time range, you don't need any date manipulation. Just remove everything after the space (assuming the format of the date_string remains consistent).

$date_string = "02/06/2011 11:00 am - 2:00 pm";
$date = explode(" ",$date_string);
echo $date[0];

Or even simpler (but untested)

echo strtok($date_string," ");  //http://codepad.org/Or1mpYOp

PHP.NET:strtok

PHP.NET:explode

Upvotes: 4

symcbean
symcbean

Reputation: 48357

Leaving aside the fact that something is going very wrong in the date parsing, you need to be aware that using a date format of 00/00/00[00] is rather ambigious - in the US dates written like this are in the format mm/dd/yy[yy] while in the UK it is interpreted as dd/mm/yy[yy]. The strtotime function does not use the locale setting to work out which applies and always assumes the former.

If I were being asked to parse this, I'd go with using preg to extract the date part. Using a pattern:

/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{2,4})/

gives an array

0=> 02/06/2011
1=> 02
2=> 06
3=> 2011

Then use mktime to generate the unix timstamp.

Other approaches include using substr to extract a fixed length string, or exploide by space to get words.

Upvotes: 0

Mchl
Mchl

Reputation: 62377

If 02/06/2011 11:00 am - 2:00 pm is what gets displayes, you're obviously displaying $date_string and not $date, because strtotime('02/06/2011 11:00 am - 2:00 pm'); returns boolean false, which date('m/d/y', $date) would convert to 01/01/1970.

Try something like this

$date_string = "02/06/2011 11:00 am - 2:00 pm";
$date_exploded = explode('-',$date_string);

$date = strtotime($date_exploded[0]);
$date = date('m/d/y', $date);
echo $date;

Upvotes: 1

Baruch
Baruch

Reputation: 21508

$date = strtotime($date_string);
$date = getdate($date);
$date = $date['mon'] . '/' . $date['mday'] . '/' . $date['year']

Upvotes: 3

Related Questions