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;
Related
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');
}
I have a timestamp in the database. With the following code I can format it to the right date:
$datefrom=mysql_real_escape_string($record['projectdatefrom']);
$date1 = date("Y/m/d", $datefrom);
Then I give the input vield the value="$date1.
Now I have another field for the H:i, so I'd like to have them seperate from each other.
Can can I cut the Y/m/d of the $date1 and only return the H:i?
Was trying doing things like this: $datetest = date("H:i", $datefrom); but no success.
$datefrom will need to be a UNIX timestamp. strtotime() can be useful for generating one off a plain-text or MySQL-style date string.
There is no need to escape the string after it was returned from the DB.
Therefore:
$date = date("Y/m/d", strtotime($record['projectdatefrom']));
$time = date("H:i", strtotime($record['projectdatefrom']));
Or using DateTime:
$dt = new DateTime($record['projectdatefrom']);
$date = $dt->format('Y/m/d');
$time = $dt->format('H:i');
In the user interface, i have a text field to enter date in dd/mm/yyyy format and there is another textbox for time in hh:mm format and another dropdown box to specify am or pm. All these three fields will let the user to enter the date,time and am/pm manually. I prefered to use this primitive method as per the requirement of the project.
Now i want all these values to be added in mysql in timestamp format to make it easier to fetch and manipulate. Please suggest me how can i achieve this.
<?
$date = '21'.'/'.'11'.'/'.'2011';
$time = '12'.':'.'00';
$ampm = "am";
$dt = DateTime::createFromFormat(
'd/m/Y h:i a',
sprintf('%s %s %s', $date, $time, $ampm),
new DateTimeZone('Country/Region'));
$mysqlDateString = $dt->format('Y-m-d H:i:s');
?>
Use mktime in conjunction with the correct format to date by sending your user input to explode, like so:
$date = '22/11/2011'; $date_pieces = explode( '/', $date);
$time = '08:35'; $time_pieces = explode( ':', $time);
$am_pm = 'PM';
$mysql_timestamp = date( 'Y-m-d H:i:s', mktime(
$time_pieces[0] + ( $am_pm == 'AM' ? -12 : 12), // Hour - Convert AM/PM to 24-hr format
$time_pieces[1], // Minute
0, // Second
$date_pieces[1], // Month
$date_pieces[0], // Day
$date_pieces[2])); // year
Now $mysql_timestamp is a valid entry for a datetime column.
If you need a UNIX timestamp, just remove the call to date, like so:
$unix_timestamp = mktime(
$time_pieces[0] + ( $am_pm == 'AM' ? -12 : 12), // Hour - Convert AM/PM to 24-hr format
$time_pieces[1], // Minute
0, // Second
$date_pieces[1], // Month
$date_pieces[0], // Day
$date_pieces[2]);
Demo
Edit: As per Phil's comments below, be sure to set a correct timezone with date_default_timezone_set.
Use DateTime::createFromFormat().
Assuming the form fields have been POSTed, roughly validated and collected into variables...
// assume $date, $time, $ampm
$dt = DateTime::createFromFormat(
'd/m/Y h:i a',
sprintf('%s %s %s', $date, $time, $ampm),
new DateTimeZone('Country/Region'));
$unixTimestamp = $dt->getTimestamp();
$mysqlDateString = $dt->format('Y-m-d H:i:s');
If you're storing the date/time as a MySQL date/time string, you should probably store the timezone as well or else it will be impossible to retrieve accurate data.
There is loads of information over at MySQL about time conversions. In your case I think str_to_date would work.
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'));
I am having the input box for getting the value in mm-dd-yyyy format.So When I get the date I try to covert it into YYYY-MM-DD format.But It doesnt work.
For Example :
<?
$birthdate="08-13-2000";
$date=date('Y-m-d',strtotime($birthdate));
echo $date;
?>.
Output is 1970-01-01.
But If I gave 13-08-2000 I got 2000-08-13.I dont want to split.Because in my application I used in manyplaces like this.But I think the strtotime convert it into unix timestamp format even whatever the value.That's why I am try to do like.What's wrong I am understanding or doing?Thanks in advance.
strtotime() parses dash-separated dates as dd-mm-yyyy. You'll need to input birthdate as "08/13/2000". str_replace should do the job for that if you can't change the expected seperator for the input.
credit for the separator differences to sam at frontiermedia dot net dot au from php.net
Edit: Have some sample code for if you need to do the replace:
$birthdate = '08-13-2000';
$birthdate = str_replace('-','/',$birthdate);
$date = date('Y-m-d',strtotime($birthdate));
echo $date;
Otherwise it'd just be
$birthdate = '08/13/2000';
... snip ...
Try this:
$date = explode("-", "08-13-2000"); // input MM-DD-YYYY
$time = mktime(0, 0, 0, $date[0], $date[1], $date[2]); // to time
$date = date('Y-m-d', $time); // transform to Y-m-d
echo $date; // output YYYY-MM-DD
$date[0] is the month
$date[1] is the day
$date[2] is the year
And if you use it in manyplaces, make a function():
function transformDate($input)
{
$date = explode("-", $input);
$time = mktime(0, 0, 0, $date[0], $date[1], $date[2]);
$date = date('Y-m-d', $time);
return $date;
}
echo transformDate("08-13-2000");