The following code snippet:
echo date("d.m.Y-H:i:s", strtotime("01.01.2000-11:12:32"));
returns me:
01.01.1970-01:00:00
What's the right way to convert "01.01.2000-11:12:32" to time/date object, for comparing it with the current timestamp?
e.g.
if (date("d.m.Y-H:i:s") > date("d.m.Y-H:i:s", strtotime("01.01.2000-11:12:32"))) {
echo "future";
} else {
echo "past";
}
This is due to localisation. Try giving a different format, as the format matters a lot:
echo date("d.m.Y-H:i:s", strtotime("01/01/2000 11:12:32"));
echo date("d.m.Y-H:i:s", strtotime("01-01-2000 11:12:32"));
You should not have . for date and month separator.
You cannot separate date and time using -.
If you are getting the input from another source, try using str_replace:
echo date("d.m.Y-H:i:s", strtotime(str_replace(array(".", "-"), array("/", " "), "01.01.2000-11:12:32")));
Output: http://ideone.com/d19ATK
Try to replace . with -:
echo date("d.m.Y-H:i:s", strtotime(str_replace('.', '-', "01.01.2000 11:12:32")));
Also remove - between the date and time.
You can use DateTime::createFromFormat
$date = DateTime::createFromFormat('d.m.Y-H:i:s', '01.01.2000-11:12:32');
$now = new DateTime();
if ($now > $date) {
echo "future";
} else {
echo "past";
}
Related
I am trying to create reg_exp for matching the given date string. In that date string following format is possible
01.12.1990
01. 12. 1990
I created the reg_exp for the first format (i.e) without space between day, month, year. But its not working for the second format too. How can i make the reg_exp which should support both and get the date?
My reg_exp is below,
$dateString = "01.12.1990";
preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1]).(0[1-9]|1[0-2]).[0-9]{4}$/",$dateString))
Use \s
Read More about Escape
$dateString = "01 . 12 . 1990";
preg_match_all("/^(0[1-9]|[1-2][0-9]|3[0-1])\s*.\s*(0[1-9]|1[0-2])\s*.\s*[0-9]{4}$/is",$dateString,$res);
print_r($res);
The following and using str_replace() will echo:
01.12.1990
Match
<?php
$dateString = "01. 12. 1990";
$dateString = str_replace(' ', '', $dateString);
echo $dateString;
if( preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1]).(0[1-9]|1[0-2]).[0-9]{4}$/",$dateString)) {
echo "<br>";
echo "Match";
}
else{
echo "<br>";
echo "No match";
}
If using $dateString = "01. 12. 1990x"; with a letter inside will echo
01.12.1990x
No match
Why do not you work with dates by the strftime?
http://php.net/manual/en/function.strftime.php
I have a MySQL database with a list of dates. I want to output all these dates, provided they occur after today, into a page. The dates are stored in the database in DATE format, as Y-m-d.
I've got the following code (excluding the query etc):
$dateToday = date('Y-m-d');
do{
$dateCompare = new DateTime($row['date']);
if ($dateCompare > $dateToday){
echo '<p>'.$dateCompare -> format('Y-m-d').'</p>';
} else {
echo '<p>FALSE</p>';
}
}while ($row = $stmt->fetch(PDO::FETCH_ASSOC));
But this just outputs all the dates, including one I have set in the past for testing purposes. What am I doing wrong?
$dateToday is a string. $dateCompare is a DateTime object.
You should use strtotime() function.
http://www.w3schools.com/php/func_date_strtotime.asp
Try and convert the date from myssql to a datetime object and output.
$changetime = new DateTime($time, new DateTimeZone('UTC'));
ECHO $changetime->format('m/d/y h:i a');
// list of timezones http://us1.php.net/manual/en/timezones.php
I actually use this to output all my MYSQL datetime data - allows me to convert to any timezone. Note, this will assume your datetime is in UTC - you should convert to your timezone.
$stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach ($stmt as $row) {
$time = strtotime($row['date']);
if ($_SERVER['REQUEST_TIME'] - $time) {
echo '<p>'. date('Y-m-d', $time) . '</p>';
} else {
echo '<p>FALSE</p>';
}
}
I have dates stored in a MySQL database like so: 2012-02-10
When i output them using PHP, is there a function I can use that will output it like so 10/02/2012
Ive tried:
$theDate = date_format($row['date'], 'd/m/Y');
echo $theDate;
but it doesnt seem to work. Any help appretiated.
PHP Version 5.3.3
You need to use date_create() before using date_format(). This is because date_format() expects a DateTime object as the first parameter.
$date = date_create($row['date']);
echo date_format($date, 'd/m/Y');
Another way to do the same thing:
$dt = new DateTime('2012-02-10');
echo $dt->format('d/m/Y');
For the PHP 5.4 users out there it can be simplified to:
echo (new DateTime('2012-02-10'))->format('d/m/Y');
edit
To comment on the alternative solutions provided, they can be simplified to:
echo date('d/m/Y', strtotime($row['date']));
Just keep in mind that they do not account for daylight savings time or timezones like DateTime does.
The old way (non-OOP) to do it,
$t = strtotime('2012-02-10');
echo date('d/m/Y', $t);
Functions to check: strtotime, date
Here's a really simple way to do it
<?php
$theDate = $row['date'];
echo date("m/d/Y", strtotime($theDate));
?>
Here are a few examples:
$input = '2012-02-10';
// datetime (object oriented style)
$dt = new DateTime($input);
echo $dt->format('d/m/Y') . "\n";
// datetime (procedural style)
$dt = date_create($input);
echo date_format($dt, 'd/m/Y') . "\n";
// strtotime
$m = strtotime($input);
echo date('d/m/Y', $m) . "\n";
// substr
echo substr($input,8,2) . "/" . substr($input,5,2) . "/" . substr($input,0,4) . "\n";
// explode
$m = explode('-', $input);
echo "$m[2]/$m[1]/$m[0]" . "\n";
// preg_match
preg_match('~^(\d+)-(\d+)-(\d+)$~', $input, $m);
echo "$m[3]/$m[2]/$m[1]" . "\n";
// sscanf
$m = sscanf($input, '%d-%d-%d');
echo "$m[2]/$m[1]/$m[0]" . "\n";
p.s. did I miss any? ;)
How to convert date from yyyy:mm:dd to yyyy-m-dd and yyyy:mm:dd (without leading zero for the month) to yyyy-m-dd (with leading zero to month)?
You could use DateTime::createFromFormat and then use DateTime::format.
Example:
$date = DateTime::createFromFormat('Y:m:d', '2012:08:02');
echo $date->format('Y-m-d');
// without leading zero for month
$date = DateTime::createFromFormat('Y:n:d', '2012:8:02');
echo $date->format('Y-m-d');
try this:
$dateFrom ="2012:8:2";
$dateTo = str_replace(":","-",$dateFrom);
$dateTo = date("Y-m-d", strtotime($dateTo));
echo $dateTo;
Use the $date=strtotime($date) function to get the date in unix timestamp. After that you can use the date("Y-m-d",$date) function to convert it to the format you want.Here's an example:
$date=strtotime($olddate);
$date=date("Y-m-d",$date);
echo $date; // Now this will show you the date in the format you wanted :)
Use the date function.
date will not understand : as a separator, so you will need to replace that with a separator that it understands, like / or -, with str_replace.
Code:
$orig_date = '2012:8:2';
$final_date = date('Y-n-d', str_replace(':', '/', $orig_date));
echo $final_date; // Result: 2012-8-02
Use date() function
echo date('Y-m-d'); // for 1st case (replacing ':' with '-')
echo date('Y-j-d'); // for 2nd case (without leading zero)
I am building a timestamp from the date, month and year values entered by users.
Suppose that the user inputs some wrong values and the date is "31-02-2012" which does not exist, then I have to get a false return. But here its converting it to another date nearby. Precisely to: "02-03-2012"..
I dont want this to happen..
$str = "31-02-2012";
echo date("d-m-Y",strtotime($str)); // Outputs 02-03-2012
Can anyone help? I dont want a timestamp to be returned if the date is not original.
You might look into checkdate.
That's because strtotime() has troubles with - since they are used to denote phrase like -1 week, etc...
Try
$str = '31-02-2012';
echo date('d-m-Y', strtotime(str_replace('-', '/', $str)));
However 31-02-2012 is not a valid English format, it should be 02-31-2012.
If you have PHP >= 5.3, you can use createFromFormat:
$str = '31-02-2012';
$d = DateTime::createFromFormat('d-m-Y', $str);
echo $d->format('d-m-Y');
You'll have to check if the date is possible before using strtotime. Strtotime will convert it to unix date meaning it will use seconds since... This means it will always be a date.
You can workaround this behavior
<?php
$str = "31-02-2012";
$unix = strtotime($str);
echo date('d-m-Y', $unix);
if (date('d-m-Y', $unix) != $str){
echo "wrong";
}
else{
echo date("d-m-Y", $unx);
}
or just use checkdate()
Use the checkdate function.
$str = "31-02-2012";
$years = explode("-", $str);
$valid_date = checkdate($years[1], $years[0], $years[2]);
Checkdate Function - PHP Manual & Explode Function - PHP Manual
Combine date_parse and checkdate to check if it's a valid time.
<?php
date_default_timezone_set('America/Chicago');
function is_valid_date($str) {
$date = date_parse($str);
return checkdate($date['month'], $date['day'], $date['year']);
}
print is_valid_date('31-02-2012') ? 'Yes' : 'No';
print "\n";
print is_valid_date('28-02-2012') ? 'Yes' : 'No';
print "\n";
Even though that date format is acceptable according to PHP date formats, it may still cause issues for date parsers because it's easy to confuse the month and day. For example, 02-03-2012, it's hard to tell if 02 is the month or the day. It's better to use the other more specific date parser examples here to first parse the date then check it with checkdate.