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.
Related
I have SQLite DB one table contains datetime field
with datatype "timestamp" REAL value is 18696.0
attach image for table structure
So, I want this 18696.0 value to be converted into MySQL Y-m-d format and result should be 2021-03-10
I have didn't found any solution online. any help would be appreciated.
SQLite timestamp converted into MySQL timestamp.
EDIT: Thankyou for updating your question with the correct number and what date it should represent.
You can achieve what you need with a function that adds the days onto the Unix Epoch date:
function realDateToYmd($real, $outputFormat='Y-m-d')
{
$date = new DateTime('1970-01-01');
$date->modify('+' . intval($real) . ' days');
return $date->format($outputFormat);
}
echo realDateToYmd('18696.0');
// returns 2021-03-10
SQLite dates stored in REAL data type stores dates as a Julian Day.
From https://www.sqlite.org/datatype3.html
REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
PHP has a jdtogregorian function, in which one comment has a handy function to convert to ISO8601 dates:
function JDtoISO8601($JD) {
if ($JD <= 1721425) $JD += 365;
list($month, $day, $year) = explode('/', jdtogregorian($JD));
return sprintf('%+05d-%02d-%02d', $year, $month, $day);
}
echo JDtoISO8601('17889.0');
// Results in -4664-11-16
The results don't exactly look right, is it definitely 17889.0 in SQLite?
If this float number 18696.0 represents the number of days since 1970-01-01 then the date can also be calculated like this:
$days = 18696.0;
$dt = date_create('#'.((int)($days * 86400)));
$mysqlDate = $dt->format('Y-m-d'); //"2021-03-10"
background information
Or simply with gmdate:
$mySqlDate = gmdate('Y-m-d',$days*86400);
The days are simply converted into seconds to get a valid timestamp for gmdate.
Try this:
<?php
echo date('Y-m-d H:i:s', 17889);
?>
Output:
1970-01-01 04:58:09
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.
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");
So i fetched the date into MSSQL's datetime type field.
E.g 2014-01-23 06:54:49.647
I need a simple way to determine if the datetime corresponds a specific month in a condition in PHP
//i wanted something like this
$getthedate = odbc_exec($connection, "SELECT date FROM sometable WHERE ..somecondition..");
$datedata = odbc_result($getthedate, 'DATE');
if($datedata = /* is january */) {
//do something
}
You can convert the time to a UNIX timestamp by using strtotime:
$timestamp = strtotime($datedata); //2014-01-23 06:54:49.647 = 1390460089
Then convert the timestamp into whatever format you want with the 'date' function:
$month = date('F', $timestamp); // Outputs: January
Then you can use $month to compare in your if statement as it returns the month of the date.
if ($month == "January") {
//do something
}
If you have a variable containing the date time string
2014-01-23 06:54:49.647
and you know it'll be in that format, simply use http://php.net/substr to get the month.
(This ignores any time zone issues since you didn't mention that.)
try this
<?php
$timestamp="2014-01-23 06:54:49.647";
$month = date('F', $timestamp);
$current_month=date('F');
if($month==$current_month)
{
//do something
}
?>
OR
<?php
$timestamp="2014-01-23 06:54:49.647";
$month = date('m', $timestamp);
$current_month=date('m');
if($month==$current_month)
{
//do something
}
check this
$datedata = "2014-10-19 12:36:00";
if(strtolower(date('F',strtotime($datedata))) == strtolower(date('F'))){
echo "success";
}else{
echo "unsucess";
}
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!