I have problem with date function in php. If I supply string in format "d.m.y" for example "01.01.01" it gets rendered as todays date which means that php gets confused.
I found:
Note:
The "Day, month and two digit year, with dots or tabs" format (dd [.\t] mm "." yy)
only works for the year values 61 (inclusive) to 99
(inclusive) - outside those years the time format "HH [.:] MM [.:] SS" has
precedence.
on: php.net site
How to override this behavior?
I know of date_create_from_format function which would work fine if I knew input will always be in format "d.m.y", but it won't.
UPDATE 1:
Code
$date = new DateTime('01.01.01');
echo $date->format('Y-m-d');
outputs 2010-10-19 and I wanted 2001-01-01.
To format a date other than now, use the second parameter. For example:
echo date("d.m.y", 1255982665);
echoes 19.10.09
Just read the documentation! PHP's site is excellent
It seems like you want to reformat a date?
mktime() gives unix timestamp from component pieces
date() gives string from unixtimestamp (or implied now)
getdate() gives assoc array from unix timestamp
I think you want -
$arr = explode($dateIn, ':'); //get array [day, month, year]
$timestamp = mktime(0,0,0, $arr[0], $arr[1], $arr[2]) //unix time stamp, a long integer representing time
date(DESIREDFORMAT, $timestamp);
check out the output formats here - http://us2.php.net/manual/en/function.date.php
function getDateFromString( $str )
{
$date = DateTime::createFromFormat( 'd.m.y', $str );
if ( $date !== false )
return $date->getTimestamp();
// you can try other common formats here
// ...
// otherwise just parse whatever there is
return strtotime( $str );
}
echo date( 'd.m.Y H:i', getDateFromString( '01.01.01' ) ); // 01.01.2001 20:14
Edit
To adjust it a bit more to get your exact output:
function getDateTimeFromString( $str )
{
$date = DateTime::createFromFormat( 'd.m.y', $str );
if ( $date !== false )
return $date;
// you can try other common formats here
// ...
// otherwise just parse whatever there is
return new DateTime( $str );
}
$date = getDateTimeFromString( '01.01.01' );
echo $date->format( 'Y-m-d' ); // 2001-01-01
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 the following function which works well but would like to check the returned date and compare with the current date if before current date to show something if current or in future show as normal.
Function:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
Call:
echo '<li class="list-group-item">Support Expires: ' . dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60 . '</li>');
Output:
2nd March 2016
So as not today's date and/or before today's date would like to echo a message, else just show the date.
In PHP it is very simple to compare two different dates using < = > like you normally compare numbers. The only step prior to this is below:
//Tell PHP that the value in variable is a date value
$date_1 = date_create("2017-05-29"); //This value can be any valid date format
date_1_formatted = date_format($date_1, "Y-m-d"); //This formats the date_1
//Now you can simply put the second date, for example, today.
$date_2 = date_create("2017-04-29"); //This value can be any valid date format
date_2_formatted = date_format($date_2, "Y-m-d"); //This formats the date_1
//For current date, it is simpler
$date_today_formatted = date("Y-m-d");
//Now you can compare these two dates easily
if ($date_1 < $date_today_formatted) {
echo "Date 1 falls before today.";
}
else {
echo "Date 1 falls after today.";
}
Hope this helps!
I managed to work it out using the following 2 functions:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
function checkLicenceSupport($licence_date) {
$date_now = new dateTime();
$date_set = dateFormat($licence_date, 11*60*60);
if ($date_now > $date_set) {
return 'date expired';
} else {
return 'date valied';
}
}
I have the following function which works well, but would like to
check the returned date and compare with the current date.
If it is before the current date, show something.
If it is the current date, or in future, show as normal.
I needed to rewrite your question, because lack of grammar and punctuation made it confusing. No offense intended.
Your call code has the closing parenthesis for your function call is placed wrongly.
dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60)
It is more readable to use full days or hours (in seconds):
11*86400 //(11 Days);
11*3600 //(11 Hours);
The function and code, as you have it now, will always return a date in the future of the date you've submitted via the call. (I can't tell from your question whether this was intended or not).
Currently, there is no "comparison" in your function. But your question indicates you want to compare the submitted date to the current date and then do something in certain cases.
If you are going to use a Unix timestamp, then there's no need for multiple formatting, compare the two dates in Unix, then format the result.
function dateCompare($submittedDate){
//This is only needed if your submitted date is not a unix timestamp already
$submittedDate = strtotime($submittedDate);
$currentDate = time(); // Creates timestamp of current datetime
if($submittedDate < $currentDate) {
//show something i.e. return "Support Has Expired";
}else {
return date('jS F Y', $submittedDate);
}
}
echo '<li class="list-group-item">Support Expires: '.dateCompare($purchase_data['verify-purchase']['supported_until']).'</li>';
Hi I am trying to fix an old piece of code created by another developer. Spent a while fixing it to work with mysqli. Anyway the last thing on my list is to fix the dates error.
there is no actual error but if you submit the form with a valid date on it always shows up in the table as 01-01-1970
Below is the piece of code which is formatting the date. The date enters this in the format DD-MM-YY.
$arr[$i] = strftime("%Y-%m-%d", strtotime($date) );
The result so far is always 01-01-1970
here are some of y attempts at fixing it all with the same output:
$arr[$i] = $date;
$arr[$i] = strtotime($date);
and many variations of the strftime settings!
have you considered using date()?
string date ( string $format [, int $timestamp = time() ] )
http://php.net/manual/en/function.date.php
so...
$arr[$i] = strftime("%Y-%m-%d", strtotime($date) );
becomes
$arr[$i] = date("Y-m-d", strtotime($date) );
Try using DateTime objects and createFromFormat, so you can explicitly define the format of your $date value
$dt = DateTime::createFromFormat('d-m-y',$date);
$arr[$i] = $dt->format("Y-m-d");
I have in issue with this code, I'm reusing it from a different script, it is reading from an xml file and converting the date/time from a node. The date in the node is as follows which is the only difference to the original script:
<od>10:15:41 01/03/13</od>
I thought I had this modified correctly but it isn't working:
$_date=$record->getElementsByTagName("od");
$_date=((!empty($_date))?$_date->item(0)->nodeValue:"");
if(strpos($_date,".")!==false)
{
$_date=substr($_date,0,strpos($_date,"."));
}
$_date=date("H:i:s m/d/Y",strtotime($_date));
$_date.=(trim($_date)!="")?"Z":"";
xmlrpc_set_type($_date, 'datetime');
Any help is much appreciated.
The date/time 10:15:41 01/03/13 is an invalid format.
Use DateTime::createFromFormat instead.
strftime will work fine with a Y-m-d H:i:s format as it's unambiguous.
On the other hand, it gets confused with H:i:s m/d/y, as it can be interpreted as H:i:s d/m/Y. Think about the date 02/03/2013 - m/d/y would suggest that it's the 3rd of Feb, whereas d/m/Y would suggest that it's 2nd of March.
In other words, to ensure we get the right date every time, we have to be more specific. date_create_from_format('H:i:s m/d/y', $_date) will give you a DateTime object corresponding to the correct date, if the date given is indeed in the 'H:i:s m/d/y' format.
// Retrieve the date string
$_date=$record->getElementsByTagName("od");
$_date=((!empty($_date))?$_date->item(0)->nodeValue:"");
// Standardize it
$_date = get_date( $_date );
$_date .= (trim($_date) != "") ? "Z" : "";
xmlrpc_set_type($_date, 'datetime');
function get_date( $rawDate ) {
// Clean date string
if(strpos($rawDate,".")!==false) {
$rawDate=substr($rawDate,0,strpos($rawDate,"."));
}
// Attempt converting from m/d/y AND m/d/Y formats
$date = date_create_from_format('H:i:s m/d/y', $rawDate);
if( false === $date ) $date = date_create_from_format('H:i:s m/d/Y', $rawDate);
if( !empty($date) ) {
return $date->format('H:i:s m/d/Y'); // Convert the date to a string again
}
// If neither works, try using strtotime instead
$date = #strtotime($rawDate);
$date = !empty($date) ? date('H:i:s m/d/y', $date) : false;
return $date;
}
Hope that helps!
I have an array which will output a date. This date is outputted in the mm/dd/yyyy format. I have no control over how this outputted so I cant change this.
Array
(
[date] => 04/06/1989
)
I want to use php to check if this date matches the current date (today), but ignoring the year. So in the above example I just want to check if today is the 6th April. I am just struggling to find anything which documents how to ignore the years.
if( substr( $date, 0, 5 ) == date( 'm/d' ) ) { ...
Works only if it's certain that the month and date are both two characters long.
Came in a little late, but here’s one that doesn’t care what format the other date is in (e.g. “Sep 26, 1989”). It could come in handy should the format change.
if (date('m/d') === date('m/d', strtotime($date))) {
echo 'same as today';
} else {
echo 'not same as today';
}
this will retrieve the date in the same format:
$today = date('m/d');
Use this:
$my_date = YOUR_ARRAY[date];
$my_date_string = explode('/', $my_date);
$curr_date = date('m,d,o');
$curr_date_string = explode(',', $date);
if (($my_date_string[0] == $curr_date_string[0]) && ($my_date_string[1] == $curr_date_string[1]))
{
DO IT
}
This way, you convert the dates into strings (day, month, year) which are saved in an array. Then you can easily compare the first two elements of each array which contains the day and month.
You can use for compare duple conversion if you have a date.
$currentDate = strtotime(date('m/d',time())); --> returns current date without care for year.
//$someDateTime - variable pointing to some date some years ago, like birthday.
$someDateTimeUNIX = strtotime($someDateTime) --> converts to unix time format.
now we convert this timeunix to a date with only showing the day and month:
$dateConversionWithoutYear = date('m/d',$someDateTimeUNIX );
$dateWithoutRegardForYear = strtotime($dateConversionWithoutYear); -->voila!, we can now compare with current year values.
for example: $dateWithoutRegardForYear == $currentDate , direct comparison
You can convert the other date into its timestamp equivalent, and then use date() formatting to compare. Might be a better way to do this, but this will work as long as the original date is formatted sanely.
$today = date('m/Y', time());
$other_date = date('m/Y', strtotime('04/06/1989'));
if($today == $other_date) {
//date matched
}
hi you can just compare the dates like this
if(date('m/d',strtotime($array['date']])) == date('m/d',strtotime(date('Y-m-d H:i:s',time()))) )