remove time stamp from string - php

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

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

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

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;

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.

If your string is already is date .
$date = substr($records[$datetime, 0, 10);

Related

Convert time from AM/PM to 24 hour [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 6 years ago.
I have a time as 5:4 pm and i want convert the time from AM/PM to 24 hour format in PHP, i try as date('H:i',strtotime('5:4 pm')) but this don't work and result is 16:00 in the event that it should be 17:04. what do i do?
DEMO: http://sandbox.onlinephpfunctions.com/code/bfd524f65ea4fa3031e55c9879aab711f31e1b37
I can not change this time.
I recommend PHP OOP way as they are always better than any procedural way(like using strtotime):
$time = '5:04 pm';
$date = DateTime::createFromFormat('g:i a', $time);
echo $date->format('H:i');//17:04
Please mind that you need to provide : 5:04 pm , you CAN NOT use 5:4 pm .
Reason is that no date format exist for minutes without a leading zero.
For reference see this:
http://php.net/manual/en/datetime.createfromformat.php
If you have to have time in that format then you will need to manipulate it after you receive your time as follows:
$time = '5:4 pm';//works for formats -> '5:4 pm' gives 17:04,'5:40 pm' gives 17:40
$time2 = str_replace(' ',':',$time);
$time3 = explode(':',$time2);
if(((int)$time3[1])<10)//check if minutes as over 10 or under 10 and change $time accordingly
$time = $time3[0].':0'.$time3[1].' '.$time3[2];
else
$time = $time3[0].':'.$time3[1].' '.$time3[2];
$date = DateTime::createFromFormat('g:i a', $time);
echo $date->format('H:i');
I hope it helps
Assuming the time string format will be same -
$time = explode(' ', '5:4 pm');
$temp = date_parse($time[0]);
$temp['minute'] = str_pad($temp['minute'], 2, '0', STR_PAD_LEFT);
echo date('H:i a', strtotime($temp['hour'] . ':' . $temp['minute'] . ' ' . $time[1]));
Output
17:04 pm
You should pass 5:04 pm instead of 5:4 pm, it seems the parameter expects 2 digits for the minute format.
Working example: http://sandbox.onlinephpfunctions.com/code/ecf968c844da50e8a9eec2dc85656f49d7d20dee
You can try this
echo date("H:i", strtotime("05:04 PM"));
Try to capitalize AM/PM
date('H:i', strtotime('5:04 PM'))
{EDIT}
Replace pm with PM using str_replace
echo date('H:i', strtotime(str_replace("pm","PM",'5:04 PM')))
Here is the code,
$time = '5:4 pm';
$arr = explode(" ",$time);
$arr1 = explode(":",$arr[0]);
foreach($arr1 as $k => $val){
$arr1[$k] = sprintf("%02d", $val);
}
$str = implode(":", $arr1)." ".$arr[1];
echo date('H:i',strtotime($str));
pure date wont work, so I am exploding it as it is special case
I hope this will work.
Thanks :)
// 24 hours format
$date = date("H:i a",time());
// just pass time() function instead of strtotime()
echo $date;
// output
// 17:04 pm
// to run a test, do reset your system time back or forward to 5:4 pm
Thanks, hope this helps.

PHP and or mysql: Make a date from some variables

Assume that i have two variables in php:
$year
$month
Then I want to make another variable:
$date
which:
$date=$year-$month-25
So, if I have 2012 in $year and 7 for $month, $date will be 2012-07-25.
Actually, I will compare it with some date in MySQL.
$year and $month are inputted by user.
anybody have a solution?
The solution either how to make $date or anything as long it can be comparred with a date in mysql.
Thanks before. ^^
You can make a unix timestamp through this:
$myDate = mktime(0, 0, 0, $month, 25, $year);
This is a pretty useful thing to have, as you can format it into all sorts of nice via:
echo date("Y-m-d", $myDate);
// Prints something like: 2012-07-25
or
echo date("l", $myDate);
// Prints something like: Monday
or
date('l jS \of F Y h:i:s A', $myDate);
// Prints something like: Monday 8th of August 2005 03:12:46 PM
You can do as follows
$complete_date = $year."-".$month."-25";
which gives you 2012-7-25
Please, read the "php manual" for concat your PHP string.
it's not
$date = $year-$month-25;
it is
$date = $year . '-' . $month . '- 25';
or
$date = $year . "-" . $month . "- 25";
but simple quote is more optimize for php string.
The solution either how to make $date or anything as long it can be
comparred with a date in mysql
The key here is use of strtotime to create and compare.
MySQL dates can be converted to integer through the use of strototime:
strtotime($mysql_date);
Then you can get time() and compare to two:
time()<>strtotime($mysql_date) // then the two dates are not equal.
You can use mktime function
$date = date('Y-m-d',mktime(0,0,0,$month,25,$year));
Well, I would use mktime to get the timestamp of the date ( http://php.net/manual/de/function.mktime.php ) and use the command unix_timestamp(date(yourfield)) in mysql to compare them.
(the date() withing unix_timestamp is only required when you save datetime values and not pure date values)
Since mysql dates are usually in this format Y-m-d by default, you can use $thedate = date('Y-m-d',mktime(0,0,0,$month,25,$year)); where $month and $year are based on the user input. Of course you have to make the user input it in the format you want by using select/lists.

Convert day, full month, year and country to YYYY-MM-DD

I'm trying to convert the string 18 December 2009 (Sweden) to 2009-12-18 but I can't figure out how. So I asking you now: how can I do this?
Thanks in advance.
You can use strtotime():
<?php
$sdate = '18 December 2009';
$timestamp = strtotime($sdate);
$d = date('Y-m-d', $timestamp);
echo "$d\n"; // 2009-12-18
If your problem is that the '(Sweden)' part is always present, you could just remove that part first:
<?php
$sdate = '18 December 2009 (Sweden)';
$sdate = preg_replace('/ \(.*\)$/', '', $sdate);
$timestamp = strtotime($sdate);
$d = date('Y-m-d', $timestamp);
echo "$d\n"; // 2009-12-18
Or with added checking:
<?php
$sdate = $oImdb->getReleaseDate();
if ($sdate !== 'n/A') {
$sdate = preg_replace('/ \(.*\)$/', '', $sdate);
$timestamp = strtotime($sdate);
$d = date('Y-m-d', $timestamp);
} else {
$d = 'n/a';
}
echo "$d\n"; // 2009-12-18
Or use sscanf():
<?php
$sdate = '18 December 2009 (Sweden)';
list($day, $month, $year) = sscanf($sdate, '%d %s %d');
$timestamp = strtotime("$day $month $year");
$d = date('Y-m-d', $timestamp);
echo "$d\n"; // 2009-12-18
I am not sure what you are doing there, but judging from the error message you wrote in your comment to JM above, I'd say you are approaching the problem from the wrong end. Quoting:
Thanks! When I try the function with $oIMDB->getReleaseDate() I get following error messages:
Fatal error: Uncaught exception 'Exception' with message DateTime::__construct() [datetime.--construct]: Failed to parse time string (<time itemprop="datePublished" datetime="2009-12-18">18 December 2009</time>) …
In other words, your getReleaseDate returns an XML string that has an attribute datetime with the value you are trying to convert the element value to. So, there is no need to convert anything, because the converted value is already there. All you have to do is use SimpleXml or DOM and access that attribute value, e.g.
$time = simplexml_load_string($oIMDB->getReleaseDate());
echo $time['datetime'];
First use Explode etc to remove the country name an store the Date and Country Name in separate strings, and then use strtotime
strtotime("18 December 2009")
strtotime(<String Variable containing date>)
It returns a timestamp, you can then use it as you want. See this for reference
Then use Date to convert the timestamp to date in the format you want.
There is also the PHP 5 DateTime object, which will allow you to capture time zones and convert time zones if start using times in addition to the date.
<?php
$sdate = '18 December 2009 (Sweden)';
$sdate = preg_replace('/ \(.*\)$/', '', $sdate);
$datetime = new DateTime($sdate, new DateTimeZone('UTC'));
echo $datetime->format('Y-m-d'); // 2009-12-18
The DateTime object will allow you to manipulate the date without any seconds arithmetic, which can be a reason to use DateTime instead of strtotime().
For example, this would add one month to your original date. Many benefits of the DateTime class.
$datetime->add(new DateInterval('P1M'));

Converting separate month, day and year values into a timestamp

I have a month value (1-12), day value (1-31), and a year value (2010,2011,2012). I also have a hour value and a minute value.
How can I give this to strtotime() in a way it can convert it to a timestamp?
why convert string to date when you already know year month and date.
use setDate funtion
<?php
$date = new DateTime();
$date->setDate(2001, 2, 3);
echo $date->format('Y-m-d');
?>
Given the variables $year $month $day $hour $minute you can do:
strtotime("$year-$month-$day $hour:$minute");
Be careful to enclose the variables with ", never in this case with '.
UPDATE (thanks to comments of #Clockwork and #Tadeck):
In case there is a variable $timeofday that represents the time of day (i.e. AM or PM),
then you can parse it this with:
strtotime("$year-$month-$day $hour:$minute$timeofday");
that is to say, just attach that variable to the end of the text.
Is strtotime the best tool for this job? What about mktime()?
$time = mktime($hour, $minute, 0, $month, $day, $year);
You can provide it to function strtotime() in many ways, as mentioned in documentation. Some examples include:
$your_time = strtotime('12/31/2011 9:59');
$your_time = strtotime('2011-12-31 9:59');
$your_time = strtotime('December 31, 2011 9:59');
etc. It really is very flexible.
You can find the list of valid formats in the documentation, and that is (from the "Compound Formats" list in the mentioned documentation) for example:
10/Oct/2000:13:55:36 -0700,
2008:08:07 18:11:31,
2008-08-07 18:11:31,
2008-07-01T22:35:17.02,
2008-07-01T22:35:17.03+08:00,
20080701T22:38:07,
20080701T9:38:07,
20080701t223807,
20080701T093807,
2008-7-1T9:3:37,
(this is really copy of the documentation)
Use it like this strtotime("YYYY-mm-DD HH:MM AM/PM"):
echo date("d F Y h:i:s A", strtotime("2011-06-01 11:15 PM")) . "\n";
OUTPUT
01 June 2011 11:15:00 PM
Y-m-d hh:mm will work
echo strtotime('2011-12-14 11:44 am');
cit #Pekka :)
strtotime($month."-".$day."-".$year)

calculating days

I want to calculate the no of days from a field where I enter the dates from calendar like 21 jan 2011, but when I use count() it will only count the whole string, how can I count the days?
I suggest you have a look at the DateTime::diff() method.
For example
$date1 = new \DateTime('21 Jan 2011');
$date2 = new \DateTime('28 Feb 2011');
$diff = $date1->diff($date2);
$days = $diff->d;
I presume your date is using the date object [ http://php.net/manual/en/function.date.php ]. If so, you could use something like this [ http://www.developertutorials.com/tutorials/php/calculating-difference-between-dates-php-051018-1024/ ] to calculate the difference between two dates. I presume that's what you're intending to do.
If you're not already using the date object, you can convert to the date object fairly easily. The tutorial linked to above demonstrates converting a string to a date using the explode function.
try this
echo date('d',strtotime('21 jan 2011'));
see this function for more strtotime
$date = "21 jan 2011";
$days = explode(" ", $date);
$days = $days[0];

Categories