Converting time stamp - php

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!

Related

If a Date exist return a calculated date

I have the code below to add days to a date.
$date = '[[lbc_dates_lbc_date]]';
$date = date('d F y', strtotime('+28 days', strtotime($date)));
echo $date;
This works perfectly for cases where a date entry actually exists, however, it's displaying an odd date for cases where date entry doesn't exist yet (blank).
Can you amend the code to say if a date exists add days, otherwise leave blank?
Please see image attached (errors in red, correct view in green)
Thanks
strtotime() will return FALSE when it can't parse the date. This is being treated as 0, the epoch time, when you use it as the base time in the second call to strtotime().
Check for that before trying to use the result.
$parsed = strtotime($date);
if ($parsed) {
$date = date('d F y', strtotime('+28 days', $parsed));
} else {
$date = '';
}
You should use DateTime object for storing and manipulating dates.
echo $date !== null ? (new DateTime($date))->add(new DateInterval('P28D'))->format('Your date format here') : '';
https://www.php.net/manual/en/class.datetime.php
Basically it uses a ternary operator to check if $date is null, if it's not, it creates a new DateTime object for the current date, adds 28 days and echoes it in a chosen format. If $date is null, it will just echo an empty string - ''.
Edit: The above is just an one-liner example, a good practice would be getting it into a function.

How to change the format of the datetime along with changing from 12 hour to 24 hour?

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

stringtotime beginning and end of the month not working proppely

I have the code:
$month = DateTime::createFromFormat('m/Y', $date);
if ($month) {
$month = $month -> format('01/m/Y');
}
echo "From ".$startMonth." to ".$endMonth = date("t/m/Y", strtotime($month));
when $date is a string like "05/2015".
This returns:
From 01/05/2015 to 31/01/2015
But for some reason the month is coming up as 01 when it should be 05?
Why is it doing this? It should be
From 01/05/2015 to 31/05/2015
Besides the unnecessary chopping and changing between DateTime objects and unix timestamps (when you could do the whole thing using DateTime objects.... you're passing a formatted date of '01/m/Y' to strtotime()... the / indicates to the strtotime() function that the date is in US date format (mm/dd/yy): and you should use '01-m-Y' (with a -) for dd-mm-YYYY if you want to tell strtotime() that it's a European format date.
See the "localized notations" table on the PHP Docs page for an explanation of formats accepted by strtotime()
However, doing the whole thing using DateTime objects:
$date = '4/2015';
$month = DateTime::createFromFormat('m/Y', $date);
echo "From " . $month->format('01/m/Y') . " to ". $month->format('t/m/Y');

Date is inserting as 0000-00-00 00:00:00 in mysql

My $date output is in the foreach loop
09/25/11, 02/13/11, 09/15/10, 06/11/10, 04/13/10, 04/13/10, 04/13/10,
09/24/09, 02/19/09, 12/21/08
My mysql query(PHP) is as follows
("INSERT INTO table_name(`field1`, `field2`,`date`) VALUES ('".$value1."','".$value2 ."','".$date."')");
Question: In my database all the dates stores as 0000-00-00 00:00:00. But 4th date (06/11/10) is stored as 2006-11-10 00:00:00.
I tried with date('Y-m-d H:i:s', $date); but no help.
Note: My database field is datetime type.
Any idea?
You're on the right track with your date('Y-m-d H:i:s',$date); solution, but the date() function takes a timestamp as its second argument, not a date.
I'm assuming your examples are in American date format, as they look that way. You can do this, and it should get you the values you're looking for:
date('Y-m-d H:i:s', strtotime($date));
The reason it's not working is because it expects the date in the YYYY-MM-DD format, and tries to evaluate your data as that. But you have MM/DD/YY, which confuses it. The 06/11/10 example is the only one that can be interpreted as a valid YYYY-MM-DD date out of your examples, but PHP thinks you mean 06 as the year, 11 as the month, and 10 as the day.
I created my own function for this purpose, may be helpful to you:
function getTimeForMysql($fromDate, $format = "d.m.y", $hms = null){
if (!is_string($fromDate))
return null ;
try {
$DT = DateTime::createFromFormat($format, trim($fromDate)) ;
} catch (Exception $e) { return null ;}
if ($DT instanceof DateTime){
if (is_array($hms) && count($hms)===3)
$DT->setTime($hms[0],$hms[1],$hms[2]) ;
return ($MySqlTime = $DT->format("Y-m-d H:i:s")) ? $MySqlTime : null ;
}
return null ;
}
So in your case, you use format m/d/yy :
$sql_date = getTimeForMysql($date, "m/d/yy") ;
if ($sql_date){
//Ok, proceed your date is correct, string is returned.
}
You don't have the century in your date, try to convert it like this:
<?php
$date = '09/25/11';
$date = DateTime::createFromFormat('m/d/y', $date);
$date = $date->format('Y-m-d');
print $date;
Prints:
2011-09-25
Now you can insert $date into MySQL.

Problem with short date format in php

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

Categories