PHP date - String to Timestamp - php

I am trying to parse date strings without having to manipulate strings and expect a given format.
I want my user to be able to enter January 2, 2011 or 1-2-11, and still end up with 2011-01-02 12:00:00 to save in a database.
Currently, I have this in place:
$post_date = date("Y-m-d H:i:s", strtotime(stripslashes($_POST['post_date'])));
But it seems strtotime is returning 0, because the datetime ends up as 1969-12-31 17:00:00
What do I need to change?
UPDATE
From php.net:
(PHP 4, PHP 5)
strtotime — Parse about any English textual datetime description into a Unix timestamp.
..I guess not!
I am not trying to strtotime( an array:
if(isset($_POST['post_date'])){
foreach($_POST['post_date'] as $id => $post_date){
print $post_date.'<br />';
if(strlen(trim($post_date)) && $post_date !== 'Date posted'){
$update_data[$id]['post_date'] = date("Y-m-d H:i:s", strtotime(stripslashes($post_date)));
}
}
}
Got it working with:
if(isset($_POST['post_date'])){
foreach($_POST['post_date'] as $id => $post_date){
print $post_date.'<br />';
if(strlen(trim($post_date)) && $post_date !== 'Date posted'){
$post_date = str_replace(',', '', $post_date);
$post_date = str_replace('-', '/', $post_date);
$update_data[$id]['post_date'] = date("Y-m-d H:i:s", strtotime(stripslashes($post_date)));
}
}
}
Thanks to multiple contributors. I remove commas and replace hyphens with forward slashes.

From the comments the OP said :
$_POST['post_date'] is actually an array (updating multiple records),
but an example value would be 'December 31, 2012'
You cannot pass a comma in the strtotime arguments alongside time, doing so would always return a 1970-01-01 00:00:00. You have to remove the user generated comma.
$post_date = date("Y-m-d H:i:s", strtotime(stripslashes("1 January 1927 17:59")));
echo $post_date; //1927-01-01 17:59:00

You really need to be concerned with your input, but here's an idea.
foreach($_POST['input'] as $userDate) {
// strtotime() will assume m/d/y or y-m-d depending on if '-' of '/' is used.
$userDate = str_replace('-', '/', $userDate);
$post_date = date("Y-m-d H:i:s", strtotime(stripslashes($userDate)));
}

In PHP 5.3.3+ (and perhaps older versions)
date('Y-m-d', strtotime('January 2, 2011'))
(notice the comma IS there) will give you 2011-01-02
However, when you add hour and minute to the end of that date phrase, strtotime DOES return 0.
date('Y-m-d', strtotime('January 2, 2011 14:30'))
Unfortunately gives you 1970-01-01 00:00:00
Notice: http://codepad.org/qgJIJSaw
Consider removing the comma:
$date = str_replace(',', '', $date);
Also, strtotime will convert '1-2-11' to 2001-02-11 (February 11th 2001), so you will probably need to rearrange the numbers if they fit the pattern, using something like:
$date = preg_replace('#^([\d]{1,2})-([\d]{1,2})-([\d]{2,4})$#', '$3-$1-$2', $date);

Related

how to do general conversion of date from different formats (some times with extra string) to Y-m-d format

In my CodeIgniter application, I am getting date in different formats, such as: April 1st 2017, May 29, 2015, Jun-15-2015, 10-September-2015 and sometimes even with extra string such as Start: April 1, 2017. However, I want to convert the input date from any format to Y-m-d in order to save it in MySQL database. For example, if input date is April 1st 2017 I should get 2017-04-01. I have used below posted code for that but it is not working for all of the above mentioned cases. So please tell how can I write general conversion logic that can convert date from any format even if date has extra string with it (as mentioned above) to Y-m-d format.
Code:
$date = DateTime::createFromFormat('F jS Y', $old_date);
$new_date = $date->format('Y-m-d');
try this
$old_date = 'Jun-15-2015';
echo $newDate = date("Y-m-d", strtotime($old_date));
You can replace the extra string like
$date = str_replace('Start: ',' ',$date);
And after you can use date function of php
echo $date = date('Y-m-d',strtotime($date));
This might help even for inserting this date format into database tables
function convertUTCCombinedToLocal($utcDateTime) {
$utcDateTime = explode(" ", $utcDateTime);
$date = explode("-", $utcDateTime[0]);
$time = explode(":", $utcDateTime[1]);
$localDate = new DateTime();
$localDate->setTimezone(new DateTimeZone('UTC'));
$localDate->setDate($date[0], $date[1], $date[2]);
if (count($time) == 3) {
$localDate->setTime($time[0], $time[1], $time[2]);
} else {
$localDate->setTime($time[0], $time[1], '00');
}
$localDate->setTimezone(new DateTimeZone('Asia/Kolkata'));
return $localDate->format('d/m/Y H:i:s');
}

php convert date to mktime function

I post a date input $_POST['date'] with format 2013/11/22 and time $_POST['time'] with format 10:10 AM. Now I need to put both inputs in the mktime function like this:
mktime(10, 10, 0, 11, 22, 2013);
How do I create this?
You can use DateTime::createFromFormat to create a DateTime object from an arbitrary format. Then you can use that object to get the timestamp (or format the date in another way):
// $_POST['date'] = '2013/11/22';
// $_POST['time'] = '10:10 AM';
$datetime = $_POST['date'] . ' ' . $_POST['time'];
$datetime = DateTime::createFromFormat('Y/m/d h:i A', $datetime);
if ($datetime) {
$timestamp = $datetime->getTimestamp();
} else {
echo 'Invalid date or time.';
}
The format in my solution (Y/m/d h:i A) expects leading zeros for all parts of the input (e.g., 2013-01-01 01:01 AM). If the input doesn't use leading zeros, you'll have to change the input format. You can see all supported format characters in the documentation.
You just use explode() function
$array = explode('/', $_POST['date']);
$arraytwo = explode (':', $_POST['time']);
In this way you'll have two array to populate mktime function.
Also the solution offered by other people will do the work.
You do not need to use mktime to it. Yeah entries are strings, then it is more consistent to use the strtotime function.
//$_POST['date'] = '2013/11/22';
//$_POST['time'] = '10:10 AM';
$dateTime = "{$_POST['date']}{$_POST['time']}";
$timeStamp = strtotime($dateTime);
if($timeStamp===false):
throw new \Exception("The date or time format is not valid!");
endif;

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'));

Php time format conversion

I have the following timeformat:15/08/2011 12:32:23 day/month/year hour:minute:sec and I want to convert to the following format: Y-m-d H:i:s
I tried with date('Y-m-d H:i:s', strtotime($time)) but it not works. It swaps the month and the day when it's converting from string to datenum.
strtotime understands both American (mm/dd/YYYY) and European (dd-mm-YYYY or dd.mm.YYYY) formats. You are using slashes to separate day, month and year, and that's why your date is interpreted as American. To solve that, replace the slashes with dashes.
In which case, you could very simply swap the month and date from your string:
$time_string = "15/08/2011 12:32:23";
$strtotime = explode("/",$time_string);
$strtotime = implode("/",array($strtotime[1], $strtotime[0], $strtotime[2]));
echo date('Y-m-d H:i:s', strtotime($strtotime));
Working Example: http://codepad.viper-7.com/234toO
You are going to have to reparse the time. strtotime is thinking you are trying to input a string in the format of 'm/d/Y H:i:s', but you are supplying 'd/m/Y H:i:s'.
list($date, $times) = explode(' ', $time);
list($day, $month, $year) = explode('/', $date);
$newTime = date('Y-m-d H:i:s', strtotime("$month/$day/$year $times");
Replace slashes with hyphen in the date then try it will work.
$a = '07/08/2019'; // 07 is day 08 is month.
echo date('Y-m-d', strtotime($a)); //output: 2019-07-08 where 07 became month.
$a = str_replace("/","-","07/08/2019"); // 07-08-2019
echo date('Y-m-d', strtotime($a)); //2019-08-07

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
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);

Categories