EDIT
Per the comment below, here's my attempt at splitting / combining / converting the string prior to implementing mktime...
$date1 = explode("T",'2005-03-27T00:00:00');
$date2 = explode("-", $date1[0]);
$try = mktime($time1,$time2,0,$date2[1],$date[2],$date[3]);
print $try;
// Prints out: 951793200
Original Question:
I've inherited a database and would like very much to convert the bizarre way the data is stored to something more mysql-friendly...
In the meantime, I get a text string (yes... text)... That I'd like to convert to unixtime...
So, I'll get a string that looks like this:
2005-03-27T00:00:00 03:00 AM
I'd like to convert it to:
1111885200
Dates and times always mess me up... I've done a number of things using strtotime and mktime, but can't get it formatted the way I want.
Well, this is how I would do it.
$ex = '2005-03-27T00:00:00 03:00 AM';
$format = '%Y-%m-%dT00:00:00 %H:%M %p';
$strf = strptime($ex, $format);
$date_str = $strf['tm_mon'] + 1 . '/' . $strf['tm_mday'] . '/' . ($strf['tm_year'] + 1900) . ' ' . $strf['tm_hour'] . ':' . $strf['tm_min'] . ':00';
echo $date_str;
echo "\n";
echo strtotime($date_str);
echo "\n";
echo date('m-d-Y H:i:s', 1111885200);
But, your desired result does not seem to be correct based on the date you posted.
OUTPUT
3/27/2005 3:0:00
1111921200
03-26-2005 17:00:00
You could write a litte converter script that does the task for you.
Please check the optional parameters of mktime
You could try to split your string in hour / minute / second / month / day / year and put that into mktime. Then mktime will give you the unix timestamp for that.
So, I'm not a fan of regular expressions unless absolutely necessary, but they might be necessary here to pick out the time zone piece.
preg_match("/(\d{4})-(\d{2})-(\d{2})(T\d{2}:\d{2}:\d{2}) (\d{2}:\d{2}) (AM|PM)/", '2005-03-27T00:00:00 03:00 AM',$matches);
Will give you $matches that look something like:
Array
(
[0] => 2005-03-27T00:00:00 03:00 AM
[1] => 2005
[2] => 03
[3] => 27
[4] => T00:00:00
[5] => 03:00
[6] => AM
)
I would feed those pieces into a DateTime object. Then you can output it into any format you want. You also may have to adjust that regex some so it can handle all your dates.
If the T00:00:00 part is useless, just remove it and use strtotime():
<?php
$date = '2005-03-27T00:00:00 03:00 AM';
$timestamp = strtotime(preg_replace('!T[^ ]+!', '', $date));
var_dump(date('d/m/Y H:i:s', $timestamp));
?>
This prints:
string(19) "27/03/2005 03:00:00"
Related
If I have this date: "16/2/2014 3:41:01 PM" and would like to change it to the format: "2014-02-16 15:41:01".
How can I do it with PHP?
I tried this:
$date = "16/2/2014 3:41:01 PM"
$newDate = date("Y-m-d H:i:s", strtotime($date));
but it keeps returning "1970-01-01 00:00:00".
The current format of your $date string is invalid in terms of how PHP reads and parses dates - See these two URLs for specifics:
http://php.net/manual/en/function.strtotime.php
http://php.net/manual/en/datetime.formats.php
Essentially, when using slashes (/) as date separators, PHP assumes you're entering MM/DD/YYYY. If at all possible, I'd see about updating whatever input created that date string to save it in MM/DD/YYYY format - That would probably be the best solution.
However, if that's not an option, based on what you've given, one method would be to swap the 16 and 2 to go from a DMY to an MDY format. Here's an example on how to do that using explode() and string concatenation:
<?php
// The original string you provided, with a date in `DD/MM/YYYY` format
$dateString = "16/2/2014 3:41:01 PM";
// The explode function will let us break the string into 3 parts, separated by the forward slashes. Using your example, these gives us an array containing the following:
// 0 => '16'
// 1 => '2'
// 2 => '2014 3:41:01 PM'
$stringPieces = explode('/', $dateString, 3);
// Piece the above array back together, switching the places of entries 0 and 1 to create a date in the format `MM/DD/YYYY`. This results in:
// 2/16/2014 3:41:01 PM"
$newDateString = $stringPieces[1] . '/' . $stringPieces[0] . '/' . $stringPieces[2];
// Use the reformatted date string in the date() function:
$newDate = date("Y-m-d H:i:s", strtotime($newDateString));
var_dump($newDate);
The output of var_dump() in my testing was string(19) "2014-02-16 15:41:01"
Use this function
Date and Time format
1: This function will help you
function date_his($date = '')
{
if ($date == '') {
return $date = date("Y-m-d H:i:s");
} else {
$date = date("Y-m-d H:i:s", strtotime($date));
}
return $date;
}
2: While store in to database call this function like this
$date = date_his();
it will consider current date and current time
3: If you want to store the date from date field call like this
$date = date_his($_POST['field_name']);
Bonus
It converts any date and time format into YYYY-mm-dd HH:mm:ss
I have problem to convert one of my dates in YYY-d-m format.
I have the array $searchQuery, which when print using print_r, prints the foloowing output:
Array ( [selectedArea] => 0
[checkin] => 30/07/2014
[checkout] => 01/08/2014
[rooms] => 1
[adults] => 2
[childrens] => 0 )
I have the following code:
echo "Checkin is:" .$searchQuery['checkin']."<br />";
$what = strtotime($searchQuery['checkin']);
echo "New checkin is:" .$newCheckin = date('Y-m-d', $what) ."<br />";
echo "Checkout is:" .$searchQuery['checkout']."<br />";
$newCheckOutTemp = strtotime($searchQuery['checkout']);
echo "New checkout is:" .$newCheckout = date('Y-m-d', $newCheckOutTemp) ."<br/>";
Which prints the following:
Checkin is:30/07/2014
New checkin is:1970-01-01 ------>????
Checkout is:01/08/2014
New checkout is:2014-01-08
I have two questions...why the first date is printing 1970-01-01 when converted, and second, how can i the difference in days between those 2 dates.
Any help will be deeply appreciated.
Regards, John
try with datetime()
$now = new DateTime(str_replace('/', '-','30/07/2014'));
echo $now->format('Y-m-d');
$newCheckOutTemp = new DateTime(str_replace('/', '-','01/08/2014'));
echo $newCheckOutTemp->format('Y-m-d');
or with date()
echo date('Y-m-d', strtotime(str_replace('/', '-',$what)));
echo $newCheckout = date('Y-m-d', strtotime(str_replace('/', '-',$newCheckOutTemp)));
For day difference here so many answers :- Date Difference in php on days?
It appears that strtotime() expects your date format to be m/d/Y. As you are passing the date starting with month 30, it doesn't know how to handle it and returns you the date 1970-01-01. If you look closely at the checkout result, it is probably not the same as you expect (8th of January instead of 1st of August).
What I would do is write a little helper function to handle all your dates.
function formatDate($date) {
return \DateTime::createFromFormat('m/d/Y', $date)->format('Y-m-d');
}
And then later use it like this:
$newCheckin = formatDate($searchQuery['checkin']);
$newCheckout = formatDate($searchQuery['checkout']);
I think you have to try: date('Y-m-d', strtotime($what)) instead of date('Y-m-d', $what)
I have a form that receives a time value:
$selectedTime = $_REQUEST['time'];
The time is in this format - 9:15:00 - which is 9:15am. I then need to add 15 minutes to this and store that in a separate variable but I'm stumped.
I'm trying to use strtotime without success, e.g.:
$endTime = strtotime("+15 minutes",strtotime($selectedTime)));
but that won't parse.
Your code doesn't work (parse) because you have an extra ) at the end that causes a Parse Error. Count, you have 2 ( and 3 ). It would work fine if you fix that, but strtotime() returns a timestamp, so to get a human readable time use date().
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the ) is the main issue here.
Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime class, which along with it's related classes, really should be in any PHP developer's toolkit.
// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');
Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:
!g:i:s 12-hour format without leading zeroes on hour
!G:i:s 12-hour format with leading zeroes
Note the ! item in format. This would set date component to first day in Linux epoch (1-1-1970)
strtotime returns the current timestamp and date is to format timestamp
$date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
$date=date("h:i:sa",$date);
This will add 15 mins to the current time
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
get After 20min time and date
function add_time($time,$plusMinutes){
$endTime = strtotime("+{$plusMinutes} minutes", strtotime($time));
return date('h:i:s', $endTime);
}
20 min ago Date and time
date_default_timezone_set("Asia/Kolkata");
echo add_time(date("Y-m-d h:i:sa"),20);
In one line
$date = date('h:i:s',strtotime("+10 minutes"));
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
Current date and time
$current_date_time = date('Y-m-d H:i:s');
15 min ago Date and time
$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));
Quite easy
$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));
How do I get the system date and time in this format:
$systime="12/january/2010 10.30 AM "
To get exactly what you've asked for, you'll need to use strtolower() and date:
$systime = strtolower(date("d/F/Y G.i")) . " " . date("A") . " ";
You need strtolower because there's no built-in way to get lowercase month values, so you need to get that part as January and then transform it to lowercase. You can't lowercase the whole thing because you seem to want AM or PM rather than am or pm.
Using date and strftime() we can get the system date.
Example:
echo date("d/F/Y g:i A");//It prints 05/March/2010 12:18 PM
echo strftime("%d/%B/%Y %I:%M %p"); //It prints 05/March/2010 12:20 PM
Try:
$systime = date('d/F/o g i A');
Sample output:
05/March/2010 7 27 AM
date() and time()
I got a code like this that works just fine.
$dates[] = date('F, Y', $date);
I wonder if it's possible to pass a variable to the first argument. Something like this (but this doesn't work):
$date_format = 'F, Y';
$dates[] = date($date_format, $date);
EDIT: This actually works just fine. Just placed the variable in the wrong place.
That's perfectly legal. As to why it doesn't work, can you provide a code snippet that doesn't work? There will be some other reason why. I run this:
$date_format = 'F, Y';
$inputs = array(time(), time() + 5000000, time() + 10000000);
$dates = array();
foreach ($inputs as $input) {
$dates[] = date($date_format, $input);
}
print_r($dates);
and get:
Array
(
[0] => November, 2009
[1] => January, 2010
[2] => March, 2010
)
date() just takes a string as it's first argument. Whether it is a literal string like your first example or a variable containing a string like the second example doesn't matter - they are equivilent.
I try your code, no problem for me.
Are you sure that your date is a time ? with the function time for example ?