Got some questions about the php date function.... Here it goes..
I use jquery's datepicker to get the date from the user in the format "day/month/Year". Eg. 23rd of november 2009 is 23/11/2009.
And to manipulate this is php i use the following code...
I store the date string in a variable $date
$dateOf = date ('(d-m-Y)', strtotime($date));
The problem i get is that when i pass the date string to the strtotime function it takes the number representing the month as the number representing the date.
Eg : When i give date as 24/12/2009 strtotime takes it as 12/24/2009
I can't get what i am doing wrong here... Will be glad if开发者_开发知识库 someone clears this up....
Thanks and Regards
On the PHP side, you can fix by doing this:
$date = "24/12/2009";
$date = preg_replace('/^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/','\2/\1/\3', $date);
$dateOf = date ('(d-m-Y)', strtotime($date));
That just swaps the position of the first and second match taking 24/12/2009
and making it 12/24/2009
Edit:
Without regex :
$date = "24/12/2009";
$date = explode('/', $date);
$date = implode('/', array($date[1], $date[0], $date[2]));
$dateOf = date ('(d-m-Y)', strtotime($date));
From the documentation:
The function expects to be given a string containing a US English date format
In the U.S., the month must come before the date, e.g. mm/dd/yyyy
Here's a workaround without Regex:
$date = explode('/', $date);
$dateOf = date('(d-m-Y)', strtotime($date[1].'/'.$date[0].'/'.$date[2]));
strtotime
parse an english date
Here's an example showing how to do it:
<html>
<head>
<title>Php Date Function</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.ui.all.packed.js"></script>
<link rel="stylesheet" src="themes/default/ui.all.css"/>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#dpicker').datepicker({
dateFormat: "dd/mm/yy"
});
})
</script>
</head>
<body>
<form action="#" method="POST">
<input size="25" readonly="readonly" type="text" value="" id="dpicker" name="dpicker" />
<br/>
<input type="submit" id="validBtn" value="OK" name="valid" />
</form>
<div>
<?php
$d = (isset($_POST['dpicker']) ? $_POST['dpicker'] : null);
if ($d) {
$ds = explode("/", $d);
$dte = date('(d-m-Y)', mktime(0, 0, 0, $ds[1], $ds[0], $ds[2]));
echo '<p>Date: ' . $dte . '</p>';
}
?>
</div>
</body>
</html>
精彩评论