How would you convert UK date to US date in PHP without much regard to separator:
e.g.
01/01/2012
to
2012-01-01
Thanks in advance!
If you don't have to invoke date and time functions, don't do it and according to your question it seems like you only need string manipulations. Use sscanf()
list($date,$month,$year) = sscanf("01/01/2012", "%d/%d/%d");
echo "$month-$date-$year";
You could use strtotime but that's a magical function so I don't trust it.
A more discreet approach is to just do a very manual conversion, like:
$us_date = "01/01/2012";
$parts = explode("/", $us_date, 3);
$uk_date = $parts[2] . "-" . $parts[0] . "-" . $parts[1]; // flip day and month?
<?php
$format1 = strtotime("01/01/2012");
//$format2 = strtotime("2012-01-01");
echo date("Y-m-d",$format1);
?>
Related
I echo this :
php> echo date("Y-m-d\TH:i:s");
2011-05-27T11:21:23
How can do with date function to get this date format:
2011-01-12T14:41:35.7042252+01:00 (for example)
35.7042252 => seconds.decimal-fraction-of-second
I have tried:
php> function getTimestamp()
... {
... return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8);
... }
php> echo getTimestamp();
2011-05-27T15:34:35.6688370 // missing +01:00 how can I do?
date('Y-m-d\TH:i:s.uP')
u for microseconds was added in PHP 5.2.2. For earlier or (still) broken versions (see comments):
date('Y-m-d\TH:i:s') . substr(microtime(), 1, 8) . date('P')
Or, to avoid two calls to date:
date(sprintf('Y-m-d\TH:i:s%sP', substr(microtime(), 1, 8)))
Best performance:
substr_replace(date('c'), substr(microtime(), 1, 8), 19, 0);
By doing separate [date] calls you have a small chance of two time stamps being out of order: eg call date at 1:29:22.999999 and mircotime at 1:29:23.000001. On my server consecutive calls are about 10 us apart.
Source
Try this instead:
list($usec, $sec) = explode(" ", microtime());
echo date("Y-m-d\TH:i:s", $sec) . substr($usec, 1, 8) . date("P", $sec);
E.g.:
2015-07-19T16:59:16.0113674-07:00
As a solution for 2020 with the DateTime class, which was added in PHP 5.2, you can do a simple one liner to get the wanted format.
For example:
echo (new DateTime())->format('Y-m-d\TH:i:s.uP');
// 2020-04-23T09:18:25.311075+02:00
The DateTimeInterface, which is implemented by the DateTime class, brings its own constants for widely used date formats. If you know the format, you can use a constant for that.
echo var_dump($datetime->format(DateTime::RFC3339_EXTENDED));
// 2020-04-23T09:18:25.311+02:00
As object orientated programming is widely spread in the PHP world, this could be a possible solution, too.
If parsing the string returned by microtime makes you vomit in your mouth, and you don't want multiple distinct timestamps munged together into your output, you can do this:
$unow = microtime(true);
sprintf("%s.%06d%s", date("Y-m-d\TH:i:s", $unow), ($unow - floor($unow))*1e6, date("P", $unow));
I have a range of dates in string format in the form of
'2014-10-12'
what i want to do is compare these dates so i can get the oldest and the youngest.
In PHP how do i convert these to a format where i can do the following?
$oldestdate;
$youngesdate;
//loop though all the dates
if($exampledate < $youngesdate)
$youesdate = $exampledate;
if($exampledate > $oldestdate)
$oldestdate = $exampledate;
Thanks
The nice thing about YYYY-MM-DD style dates is that they will always sort correctly, whether treated as text (as in your example), numbers (e.g. 20141012), or actual dates.
Thus, there's no need to do anything special to compare them as long as everything is the same format. Your code, as written, should work as-is (besides the typos for $youngestdate).
Note that if you want to do anything besides comparing them -- e.g. anything actually involving treating them like actual dates -- you will indeed want something like strtotime() or a mix of mktime() + substr()
have you tried strotime? reference http://php.net/manual/de/function.strtotime.php
then you can easily compare with <and > and so on.
have you tried checkdate(12, 31, 2000)? PHP.net Checkdate function
For years between 1 and 32767 inclusive.Check post 2 in the php.net link
You should use the DateTime class.
$arr = ['2012-10-12', '2004-10-12', '2014-08-12', '2014-09-12', '2014-09-13', '2014-09-11'];
$_now = new DateTime('now');
foreach ( $arr as $_t ) {
$d = new DateTime ( $_t );
if ( !isset($newest) || $d >= $newest ) $newest = $d;
if ( !isset($oldest ) || $d <= $oldest ) $oldest = $d;
}
echo 'Newest ' . $newest->format('Y-m-d');
echo 'Oldest' . $oldest->format('Y-m-d');
Take a look here: Reference on php.net
And here is an working example
How can I force the date format to output:
12/12/2012, 1/10/2012, 1/5/2012
instead of
12/12/2012, 01/10/2012, 01/05/2012?
My code is the following:
$adatefrom = date_create($_POST['datefrom']);
$adateto = date_create($_POST['adateto']);
$adatefrom = date_format($adatefrom, 'd/m/Y');
$adateto = date_format($adateto, 'd/m/Y');
Please do note that I have to format the date AFTER posting it.
Have a look at the PHP built in date function here
You will find that your solution is as simple as this:
date('j/n/Y',strtotime($_POST['datefrom']));
The key things to note are the characters used in the first parameter.
j represents the day without leading zeros
n represents the month without leading zeros
There are many other options you have, just have a read through the documentation.
Please note that a simple search of 'PHP date' on Google would have found this solution for you
$adatefrom = date_create($_POST['datefrom']);
$adateto = date_create($_POST['adateto']);
$adatefrom = date_format($adatefrom, 'j/n/Y');
$adateto = date_format($adateto, 'j/n/Y');
you are welcome! ;)
I'm trying to convert the string 11/24/2011 # 01:15pm to a UNIX timestamp. The format is m-d-Y # h:ia
I can't seem to get strtotime to work with the string. Is there a way to reverse the data function? Is my only choice to create a new non-default php function to convert the string?
The server is running CentOS 5, Apache 2.2 and PHP 5.2.17.
Use the more modern DateTime class (so long as you're using >= 5.3).
$unix = DateTime::createFromFormat('m/d/Y # h:ia', '11/24/2011 # 01:15pm')
->getTimestamp();
CodePad.
Under PHP 5.2, you can use strptime to parse a date-time string with a specific format, then use mktime to convert the result to a timestamp.
$timeString = '11/24/2011 # 01:15pm';
$timeArray = strptime($timeString, '%m/%d/%Y # %I:%M%p');
$timestamp = mktime(
$timeArray['tm_hour'], $timeArray['tm_min'], $timeArray['tm_sec'],
$timeArray['tm_mon']+1, $timeArray['tm_mday'], $timeArray['tm_year']+1900
);
This should be abstracted as a function, possibly two:
function strptimestamp($date, $fmt) {
$timeArray = strptime($date, $fmt);
return mktime(
$timeArray['tm_hour'], $timeArray['tm_min'], $timeArray['tm_sec'],
$timeArray['tm_mon']+1, $timeArray['tm_mday'], $timeArray['tm_year']+1900
);
}
function strpmy($date) {
return strptimestamp($date, '%m/%d/%Y # %I:%M%p');
}
Support for parsing the period abbreviation appears to vary from OS to OS. If the above doesn't work on a particular OS, try "%P" instead of "%p" or pass the time string through strtoupper (or both). The following should work under any OS, though it's preferable to get strptime to handle the entirety of the parsing, as the following is less suitable as the basis for a generic strptimestamp function.
static $pm_abbrevs = array('pm' => 1, 'p.m.' => 1, 'µµ' => 1, 'µ.µ.' => 1);
$timeString = '11/24/2011 # 01:15pm';
$timeArray = strptime($timeString, '%m/%d/%Y # %I:%M');
$period = strtolower($timeArray['unparsed']);
if (isset($pm_abbrevs[$period])) {
$timeArray['tm_hour'] += 12;
}
$timestamp = mktime(
$timeArray['tm_hour'], $timeArray['tm_min'], $timeArray['tm_sec'],
$timeArray['tm_mon']+1, $timeArray['tm_mday'], $timeArray['tm_year']+1900
);
If you replace the ' # ' with a space, then strtotime should be able to understand it natively.
<?php
$x = "11/24/2011 # 01:15pm";
$x = str_replace(" # ", " ", $x);
$y = strtotime($x);
$z = date("m-d-Y # h:ia", $y);
echo "x: $x<br />\n";
echo "y: $y<br />\n";
echo "z: $z<br />\n";
?>
Output:
x: 11/24/2011 01:15pm
y: 1322140500
z: 11-24-2011 # 01:15pm
Case sensitivity may be your issue http://php.net/manual/en/datetime.formats.php.
Perhaps run $x through strtoupper() first then str_replace('#', '', $x) (notice it's replacing # with an empty string), then try strtotime(). Hope this helps.
$search = array('/',',','#');
$replace = array('-','','');
echo strtotime( str_replace($search,$replace,'16/7/2013 # 7:30AM') );
this will replace the parts of the string in the time string you are trying to convert into a format that is acceptable to strtotime. You can always add more string parts you want to replace to the arrays.
Also you dont need to have latest php for this.
Output:
1373952600
im trying to validate a date to see if it matchs the mysql format
this is the code
$match = "/^\d{4}-\d{2}-\d{2} [0-2][0-3]:[0-5][0-9]:[0-5][0-9]$/";
$s = $this->input->post("report_start"). " " . $this->input->post("report_start_time").":00";
$e = $this->input->post("report_end"). " " . $this->input->post("report_end_time").":59";
if($this->input->post("action") != "")
{
echo trim($s). " => " . preg_match($match, trim($s));
echo "<br>";
echo trim($e). " => " . preg_match($match, trim($e));
}
the date format goes into $s and $e are
$s = 2011-03-01 00:00:00
$e = 2011-03-01 23:59:59
and they both return false (0).
i tested the pattern on http://www.spaweditor.com/scripts/regex/index.php and it returns true (1)
http://pastebin.com/pFZSKYpj
however if i manual inter the date strings into preg_match like
preg_match($match, "2011-03-01 00:00:00")
it works.
i have no idea what im doing wrong
======================
now that i think about it, i only need to validate the houre:min part of the datetime string.
im manually adding the seconds and the date is forced by a datepicker and users cant edit it
You're making your work harder that it needs to be. In php there are many date handling functions that mean you don't have to treat dates like strings. So, rather than test that your input dates are in the correct format, just insist on the correct format:
$adate= date_create('January 6, 1983 1:30pm'); //date format that you don't want
$mysqldate= $adate->format("Y-m-d h:i:s");//date format that you do want
There are also functions to check that a date is a real date, like checkdate.
ok heres wat i did.
since im forcing the date format and the ending seconds of the time part
i just validated the hour:mini part using "/^2[0-3]|[01][0-9]:[0-5][0-9]$";
and if that returns true i put everything together end reconstructed the final datetime string
$match = "/^2[0-3]|[01][0-9]:[0-5][0-9]$/";
$s_d = $this->input->post("report_start");
$s_t = $this->input->post("report_start_time");
$e_d = $this->input->post("report_end");
$e_t = $this->input->post("report_end_time");
if($this->input->post("action") != "")
{
if(
( preg_match($match , trim($s_d." ".$s_t.":00")) )
&& ( preg_match($match , trim($e_d." ".$e_t.":59")) )
)
{
$r = $this->model_report->client_hours_logged(array($s,$e));
$data['report'] = $r;
var_dump($r);
//$this->load->view("report/client_hours_per_client",$data);
}
}
Watch out:
[0-2][0-3] is not a good regex for hour values - it will match 01, 12, 23 and others, but it will fail 04 through 09 and 14 through 19.
Better use (2[0-3]|[01][0-9]) instead.
I use this to validate a 'Y-m-d H:i:s' format date string:
match = '/^[12][0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[01]) ([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/';
You could use strtotime and date to parse and format the date properly.
Why not just simply force the date into the format you want:
$e = '2011-03-01 00:00:00';
$mysqlFormat = date('Y-m-d H:i:s', strtotime($e));
Also, there is a bit of an error in your regex [0-2][0-3]:[0-5][0-9]:[0-5][0-9] will only match the hours of 00,01,02,03,10,11,12,13,20,21,22,23 so it will never match 4am, or 3pm among others. That aside I looked over your RegEx and I don't see any problems with it matching the test cases you've offered. I would check to make sure there is not extra whitespace on either side of date string with trim().
I concur with Tim : MySQL behaves in quirks mode and always tries to go easy on DATE and DATE_TIME column types. You can omit certain parts of your input and it still will try to compensate and achieve that goal successfully to some degree... That's why, most numbers your Reg-ex considers as invalid, MySQL will accept as valid.