I currently am working with a database that has a month column and a year column.. Both are of type text. Month is stored as 'January' and year is stored as you would expect, '2016'..
Any recommendations for concatenating these and converting them to a date type?
You can use a query like this. you only must change the strings to your fieldnames:
sample
select STR_TO_DATE(concat('2016',' ','April','1'), '%Y %M %D');
result
2016-04-01
$months = [
'january' => 1,
'february' => 2,
'march' => 3,
'april' => 4,
'may' => 5,
'june' => 6,
'july' => 7,
'august' => 8,
'september' => 9,
'october' =>10,
'november' =>11,
'december' =>12
];
$year = 2016;
$month_text = 'january';
$day = 1;
if($months[strtolower($month_text)]<10){
$month = '0'.$months[strtolower($month_text)];
}else{
$month = $months[strtolower($month_text)];
}
if($day<10){
$day = '0'.$day;
}else{
$day = $day;
}
echo $year.'-'.$month.'-'.$day;
create a new feld in db with type date and insert it into the db. maybe wrap this in a function and put it in a while loop..?
This works for me:
select convert(date,(concat('January',' ','2016')))
Related
This question already has answers here:
Create a new date from php array
(3 answers)
Closed 4 years ago.
For a project, i need to convert multiple values form an array to a time format in PHP. I've got arrays like this:
starttime = ['year' => 2019, 'month' => 5, 'day' => 10, 'hour' => 20, 'minute' => 15]
Is there a way to convert these values to a time format with which i can also calculate stuff? I already tried using strtotime, but it dind't work. Thanks for your answers!
I suggest using the DateTime object which has the setDate, setTime and getTimestamp methods. Which you can use for defining the date and time from the array keys, and retrieve the unix timestamp as a result.
Example: https://3v4l.org/o3lVr
$starttime = ['year' => 2019, 'month' => 5, 'day' => 10, 'hour' => 20, 'minute' => 15];
$date = new \DateTime();
$date->setDate($starttime['year'], $starttime['month'], $starttime['day']);
$date->setTime($starttime['hour'], $starttime['minute']);
var_dump($timestamp = $date->getTimestamp());
var_dump(date('Y-m-d H:i:s', $timestamp));
Results:
int(1557512100)
string(19) "2019-05-10 20:15:00"
Optionally to prevent issues with missing keys, in PHP >= 7.0 you can use the null coalesce operator ?? to default the values to the current date.
Example: https://3v4l.org/0MOI5
$starttime = ['month' => 5, 'day' => 10, 'minute' => 15];
$date = new \DateTime();
$date->setDate($starttime['year'] ?? $date->format('Y'), $starttime['month'] ?? $date->format('m'), $starttime['day'] ?? $date->format('d'));
$date->setTime($starttime['hour'] ?? $date->format('H'), $starttime['minute'] ?? $date->format('i'));
var_dump($timestamp = $date->getTimestamp());
var_dump(date('Y-m-d H:i:s', $timestamp));
Results:
int(1557497700)
string(19) "2019-05-10 16:15:00"
Alternatively you can also use mktime to produce the same result. Please note, as per the manual, in PHP < 5.1.0 this method may produce unexpected (but not incorrect) results if DST is not specified.
Example: https://3v4l.org/DU0Q1
$starttime = ['year' => 2019, 'month' => 5, 'day' => 10, 'hour' => 20, 'minute' => 15];
$timestamp = mktime(
$starttime['hour'],
$starttime['minute'],
0,
$starttime['month'],
$starttime['day'],
$starttime['year']
);
var_dump($timestamp);
var_dump(date('Y-m-d H:i:s', $timestamp));
Results:
int(1557512100)
string(19) "2019-05-10 20:15:00"
I want to know how or if I can use the content of a column in mysql as a key (index) to a php array within the mysql query.
Example:
Column name: period
Column contents: (one of) 'Year','Month','Fortnight','Week','Hour','Day'
My php array:
$x = array(
'Year' => 1,
'Month' => 12,
'Fortnight' => 26,
'Week' => 52,
'Hour' => 1872,
'Day' => 365
);
Another variable $y can be any number (say < 1,000,000)
I want to write a WHERE (or HAVING) condition such as...
WHERE '$x[`period`]' * '$y' > 12345
E.g. when the contents of period = 'Month', $y should be multiplied by 12 before being tested to be > 12345
What is the best (most efficient) way to do this, other than (say) a long CASE conditional?
Thank you
i have write demo query
<?php
$x = array(
'Year' => 1,
'Month' => 12,
'Fortnight' => 26,
'Week' => 52,
'Hour' => 1872,
'Day' => 365
);
$y=10;
$sql="select * from table where ".$x['Month']*$y." > 12345" ;
echo $sql;
in $x[] select your value to multiply
You can use case instead of php array:
<?php
$y = 100;
$sql = "select * from tablename
where (case `period`
when 'Year' then 1
when 'Month' then 12
when 'Fortnight' then 26
when 'Week' then 52
when 'Hour' then 1872
when 'Day' then 365
end) * {$y} > 12345";
Try this:
<?php
$y = 10;
$period = "Month";
$x = array(
'Year' => 1,
'Month' => 12,
'Fortnight' => 26,
'Week' => 52,
'Hour' => 1872,
'Day' => 365
);
$sql="select * from table where ".($x[$period] * $y)." > 12345" ;
echo $sql;
I've got bunch of birthdays which are stored in format DDMMMYY. I need to convert those to date values, so i can store those in database.
Is there any easy way of telling strtotime function that date must be in the past?
<?php
$datestring = '22SEP41';
echo date('Y-m-d',strtotime($datestring)); //outputs 2041-09-22, should be 1941-09-22
?>
<?php
$datestring = '22SEP41';
$matches = [];
preg_match('/([0-9]{2})([A-Z]{3})([0-9]{2})/', $datestring, $matches);
$prefix = ($matches[3] <= date('y') ? '20' : '19');
$matches[3] = "{$prefix}{$matches[3]}";
$ts = strtotime("{$matches[1]} {$matches[2]} {$matches[3]}");
// date ('Y-m-d', $ts) == 1941-09-22
This assumes that 22SEP06 should be interpreted as 2006 rather than 1906 - basically it gives the output a range of 1917 -> 2016.
This method create a date of past century only if standard evaluated date is after today:
$date = date_create( $datestring );
if( $date->diff( date_create() )->invert )
{
$date->modify( '-100 years' );
}
echo $date->format( 'Y-m-d' );
For
$datestring = '22SEP41';
the output is:
1941-09-22
For
$datestring = '22SEP01';
the output is:
2001-09-22
eval.in demo
Basically, we create a DateTime based on given string, then we calculate difference with current day; if the difference is negative (->invert), we subtract 1 century from the date.
You can personalize the condition using ->format('%R%Y') instead of ->invert. In this example:
if( $date->diff( date_create() )->format('%R%Y') < 10 )
Dates from 00 through 05 as evaluated as 2000-2005.
You could try something like:
$ds = '22SEP41';
$day = $ds[0].$ds[1];
// Getting the month.
$mon = array(
'JAN' => 1,
'FEB' => 2,
'MAR' => 3,
'APR' => 4,
'MAY' => 5,
'JUN' => 6,
'JUL' => 7,
'AUG' => 8,
'SEP' => 9,
'OCT' => 10,
'NOV' => 11,
'DEC' => 12
);
$mont = $ds[2].$ds[3].$ds[4];
$month = $mon[$mont]; // Gets the month real.
$year = '19'.$ds[5].$ds[6];
$final = $day.'-'.$month.'-'.$year;
I tested it on my local machine and it worked. Hope it works and is what you're looking for :)
Date and time are setted to Madrid's standard UTC, and stored for translation and formatting in this way:
date_default_timezone_set('Europe/Madrid');
$dia=""; $mes=""; $dia2=""; $ano=""; $horaActual=""; $minutoActual="";
$dia=date("l");
if ($dia=="Monday") {$dia="Lunes";} if ($dia=="Tuesday") {$dia="Martes";} if ($dia=="Wednesday") {$dia="MiƩrcoles";} if ($dia=="Thursday") {$dia="Jueves";} if ($dia=="Friday") {$dia="Viernes";} if ($dia=="Saturday") {$dia="Sabado";} if ($dia=="Sunday") {$dia="Domingo";}
$mes=date("F");
if ($mes=="January") {$mes="Enero";} if ($mes=="February") {$mes="Febrero";} if ($mes=="March") {$mes="Marzo";} if ($mes=="April") {$mes="Abril";} if ($mes=="May") {$mes="Mayo";} if ($mes=="June") {$mes="Junio";} if ($mes=="July") {$mes="Julio";} if ($mes=="August") {$mes="Agosto";} if ($mes=="September") {$mes="Setiembre";} if ($mes=="October") {$mes="Octubre";} if ($mes=="November") {$mes="Noviembre";} if ($mes=="December") {$mes="Diciembre";}
$dia2=date("d");
$ano=date("Y");
$horaActual=date("H");
$minutoActual=date("m");
This gives the same time and date all the time (I created this an hour ago), not refreshing while web browser does. In this right moment, this code:
<?php echo "$dia $dia2 de $mes, $horaActual:$minutoActual"; echo "--" date("F j, Y, g:i a");?>
Shows:
Lunes 26 de Mayo, 16:05 -- May 26, 2014, 5:03 pm
So date() is getting the correct and updated info, but variables are not updating this info, showing stucked data from the first time they stored this values.
every time user gets inside this url, date and time must be updated with actual values
I dont know how your time got stuck, but alternatively you could do this (time updated). Consider this example:
date_default_timezone_set('Europe/Madrid');
$dia = $mes = $dia2 = $ano = $horaActual = $minutoActual = "";
$days = array('Monday' => 'Lunes', 'Tuesday' => 'Martes', 'Wednesday' => 'MiƩrcoles', 'Thursday' => 'Jueves', 'Friday' => 'Viernes', 'Saturday' => 'Sabado', 'Sunday' => 'Domingo');
$months = array('January' => 'Enero', 'February' => 'Febrero', 'March' => 'Marzo', 'April' => 'Abril', 'May' => 'Mayo', 'June' => 'Junio', 'July' => 'Julio', 'August' => 'Agosto', 'September' => 'Setiembre', 'October' => 'Octube', 'November' => 'Noviembre', 'December' => 'Diciembre');
$dia = date("l");
$mes = date("F");
$dia2 = date("d");
$ano = date("Y");
// $horaActual = date("H");
// $minutoActual = date("m");
$time = date('H:i');
echo "$days[$dia] $dia2 de $months[$mes], $time"; echo "--". date("F j, Y, g:i a");
// outputs: Lunes 26 de Mayo, 17:21--May 26, 2014, 5:21 pm
Fiddle
echo date("m", strtotime("january"));
Returns 01 as expected
echo date("m", strtotime("february"));
But this returns 03
Anyone else encountered this problem?
PHP Version 5.1.6
Today is the 29th. There is no 29th in February this year and because you're not specifying a day in February, it's using "today". The strtotime function uses relative dates so the 29th of February is basically the 1st March this year.
To solve your problem:
echo date("m", strtotime("February 1"));
As strtotime() only handles English date formats, you should maybe try using this function that I just made for you. With this you can handle month names in other languages too.
Don't know if this is essential to your application, but now you have it.
function getMonth($month, $leadingZero = true) {
$month = strtolower(trim($month)); // Normalize
$months = array('january' => '1',
'february' => '2',
'march' => '3',
'april' => '4',
'may' => '5',
'june' => '6',
'july' => '7',
'august' => '8',
'september' => '9',
'october' => '10',
'november' => '11',
'december' => '12',
'dezember' => '12', // German abrevation
'marts' => '3', // Danish abrevation for March
);
if(isset($months[$month])) {
return $leadingZero ? substr('0' . $months[$month], -2) : $months[$month];
} else {
return false;
}
}