I have a column in a MySQL table that is of type 'datetime'.
How do I get a value from php of the current date and time with the format - for example: "2014-11-09 15:06:51" and set into a variable?
thanks.
check this PHP documentation for more clarification.
$DateTime = date('Y-m-d H:i:s');
Ref
You can use CURDATE() of MySql. No need of using php for this.
INSERT INTO `db`.`data1` (
`id` ,
`date`
)
VALUES (
'2', CURDATE()
)
See for more documentation http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_curdate
Well if you're doing this in a class you could use my DateTime getter and setter. Assumes that $this->Date is a php DateTime object and you're using mysql with a DATETIME column.
Here's what using it looks like:
$this->setDate($whatever_date); // give it a timestamp, mysql DATETIME, or anything that can be read by strtotime()
// Need to put the date into mysql? Use this:
$this->getDate('mysql');
// Need to get the date so a person can read it?
$this->getDate('human');
// want it as a timestamp?
$this->getDate('unix');
Here's the methods:
// accepts 'human', 'mysql', 'unix', or custom date() string
function getDate($format='human'){
if(get_class($this->Date)!='DateTime') return FALSE;
try{
switch ($format) {
case 'human':
return $this->Date->format('M j, Y g:i a'); // Show date and time
// return $this->Date->format('M j, Y'); // Just the date
break;
case 'mysql':
return $this->Date->format('Y-m-d H:i:s');
break;
case 'unix':
return $this->Date->format('U'); // may return a negative number for old dates
break;
default:
return $this->Date->format($format);
break;
}
} catch (Exception $e){
throw new Exception('Can not use that format for getting DateTime');
return FALSE;
}
}
// Sets as a DateTime object - accepts either a timestamp or a date() string
function setDate($date){
try{
if(is_numeric($date) && (int)$date==$date){ // timestamp
$this->Date = new DateTime(date('F j, Y, g:i a', $date));
} else {
$this->Date = new DateTime($date);
}
} catch (Exception $e){
throw new Exception('Can not set the given value ('.$date.') as DateTime');
return FALSE;
}
return TRUE;
}
If you're not using classes you would want to combine them into a single function that takes the format you have and returns the format you need.
Related
i can't get this function to work. I would like to change the css class based on the acf date field and current day. (sorry, this is my first post here)
function banner_change($match_id){
$datamatch = get_post_meta($match_id, 'data', true);
$today = date("Y-m-d");
if($datamatch >= $today ){
return 'banner-si';
}
else if($datamatch < $today){
return 'banner-no';
}
}
If the returned value from get_post_meta is a datestring rather than a proper date object you need somehow to convert that to a usable date object. It is usually most convenient to use the DateTime class as per the modified banner_change function below.
function banner_change( $id=false ){
# fetch the date string
$str=get_post_meta( $id, 'data', true );
# create 1st DateTime using returned data
$date=DateTime::createFromFormat( 'Y-m-d', $str );
#create 2nd DateTime as now.
$now=new DateTime();
# find difference in days between two dates
$diff=$date->diff( $now )->d;
# format return value
return $diff > 0 ? 'banner-si' : 'banner-no';
}
$res=banner_change( 303 );
echo $res; // ex: banner-si
I've realised my DateTime function is not converting and returning false.
Example date/time as provided by Amazon. This is what I am trying to convert from:
2020-07-28T23:00:00Z
Function which accepts the date as provided by Amazon and tries to convert it.
protected function dateUtcToEuropeLondon($date)
{
try {
$dt = new DateTime($date, new DateTimeZone('UTC'));
$dt->setTimezone(new DateTimeZone('Europe/London'));
return $dt;
} catch (Exception $e) {
return false;
}
}
Full function.
// Detect if custom shipping date exists
$date = (isset($order_details->EarliestShipDate)) ? $order_details->EarliestShipDate : '';
// Set custom meta field so we can easily access it via WC_Order
if (!empty($date)) {
$date = $this->dateUtcToEuropeLondon(strtotime($date));
if ($date instanceof DateTime) {
update_post_meta($order_id, '_wpl_shipping_date', $date->format('Y-m-d\TH:i:s'));
}
}
For starters, I checked what value I got back from:
$date = $this->dateUtcToEuropeLondon(strtotime('2020-07-28T23:00:00Z'));
it was nothing: ''.
The problem is that you're trying to create a DateTime object using a UNIX timestamp (via strtotime) which is all numbers. What DateTime is expecting is the more 'human friendly' d/m/y style format - so you'll need to specify that what you're giving it is a 'unixtime' string, rather than a 'datetime' string -- subtle difference.
Try changing
$dt = new DateTime($date, new DateTimeZone('UTC'));
to
$dt = new DateTime('#'.$date, new DateTimeZone('UTC'));
Using an # at the start of the string will tell your DateTime object that you're sending in a unix timestamp. Once it's happy, it will then allow your function to determine the correct timezone from UTC to Europe/London (GMT/BST).
How to check string on date in laravel?
I want to handle the situation if string doesn't date for example like "it's some not date string".
I try it code, but it doesn't work I have next error:
InvalidArgumentException : A two digit month could not be found
Data missing
My code:
if (Carbon::createFromFormat('m-d-Y', $rowMatrix[4]) !== false) {
//
}
You can use DateTime for this purpose :
$dateTime = DateTime::createFromFormat('d/m/Y', $rowMatrix[4]);
$errors = DateTime::getLastErrors();
if (!empty($errors['warning_count'])) {
// Not a date
}
Or you can check it like this :
if (date('Y-m-d H:i:s', strtotime($rowMatrix[4])) == $rowMatrix[4]){
// it's a date
}
You can use try/catch block:
try {
$date = Carbon::createFromFormat('m-d-Y', $rowMatrix[4])
} catch(InvalidArgumentException $e) {
$date = 'Not a date';
}
But a much better way is to use Laravel validation date_format rule to make sure the string is a date:
'some_date_field' => 'date_format:"m-d-Y"',
I'm using the below method to convert the UTC time to an other time zone. But the below method seems to returning back the UTC time. Will any of you be kind enough to point out whats wrong in the method I'm using?
static function formatDateMerchantTimeZone($t, $tz) {
if (isset($t)) {
return date('Y-m-d H:i:s', strtotime($t , $tz));
} else {
return null;
}
}
$t is the datetime I pass
$tz is the time zone such as America/Los_Angeles
It surprises me that many people are unaware of, or do not use the DateTime classes. They make tasks like this almost trivial.
I have assumed that the date string you pass to the function is in the UTC timezone.
function formatDateMerchantTimeZone($t, $tz)
{
$date = new \DateTime($t, new \DateTimeZone('UTC'));
$date->setTimezone(new \DateTimeZone($tz));
return $date->format('Y-m-d H:i:s');
}
See it working
Strtotime converts a timestamp in string format to a valid date time like '09-29-2013 07:00:00' as second parameter, it does not convert a timezone to a time. php has numerous functions for timezones such as timezone_offset that does calculate the difference between two timezones. take a look in the documentation for more info:
http://php.net/manual/en/function.timezone-offset-get.php
static function formatDateMerchantTimeZone($t, $tz) {
if (isset($t)) {
date_default_timezone_set($tz);
return date('Y-m-d H:i:s', strtotime($t));
} else {
return null;
}
}
From php.net first comment.
To avoid frustrating confusion I recommend always calling
date_default_timezone_set('UTC') before using strtotime().
Because the UNIX Epoch is always in UTC; you will most likely output the wrong time if you do not do this.
try this:
<?php
/** Returns the offset from the origin timezone to the remote timezone, in seconds.
* #param $remote_tz;
* #param $origin_tz; If null the servers current timezone is used as the origin.
* #return int;
*/
function get_timezone_offset($remote_tz, $origin_tz = null) {
if($origin_tz === null) {
if(!is_string($origin_tz = date_default_timezone_get())) {
return false; // A UTC timestamp was returned -- bail out!
}
}
$origin_dtz = new DateTimeZone($origin_tz);
$remote_dtz = new DateTimeZone($remote_tz);
$origin_dt = new DateTime("now", $origin_dtz);
$remote_dt = new DateTime("now", $remote_dtz);
$offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
return $offset;
}
?>
Examples:
<?php
// This will return 10800 (3 hours) ...
$offset = get_timezone_offset('America/Los_Angeles','America/New_York');
// or, if your server time is already set to 'America/New_York'...
$offset = get_timezone_offset('America/Los_Angeles');
// You can then take $offset and adjust your timestamp.
$offset_time = time() + $offset;
?>
Now I sq use the DateTime class to convert to different time formats and I find it very useful except one feature. Before when the user try to add date but for some reason skip the time I got 00:00:00 for the time which was good enough for me. Now, with the DateTime class if the time is not included it return error.
Here is my code:
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false)
{
throw new Exception("Invalid date");
}
$formattedDate = $dt->format('Y-m-d H:i:s');
Every time I try to insert date without time I get Invalid date error. Is there a way to insert zeros on the place of the time, except getting error for this?
Thanks
Leron
Some simple pre-validation:
$date['event_time'] = trim($date['event_time']);
if (preg_match('/^\d{2}\.\d{2}\.\d{4}$/', $date['event_time'])) {
$date['event_time'] .= ' 00:00:00';
} else if (!preg_match('/^\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}:\d{2}$/', $date['event_time'])) {
die('Invalid format');
}
If you don't want to use regex I guess this should work too. If i was you I would use #deceze solution instead of this :P but for the sake of completeness, here it is:
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false)
{
$data['event_time'] = trim($data['event_time']);
$data['event_time'] .= " 00:00:00";
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time')
if ($dt === false) {
throw new Exception("Invalid date");
}
}
$formattedDate = $dt->format('Y-m-d H:i:s');