Converting birthday in format DDMMMYY to date value in PHP - php

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 :)

Related

PHP convert multiple array-values to time format [duplicate]

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"

Converting Mysql text to date

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')))

Date and time stored on variables don't refresh while page

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

WordPress localisation of german date string

Hi #ll and greetings from Germany,
Perhaps I am too blind to see, but I am struggling with a localisation problem. I hope that someone has a solution for that.
In a function I have a german date string, assume it's today:
$datestring = '3. März 2014'
Second, i have the date format used in WP
$date_format = get_option( 'date_format' );
What I am trying to achive is to get a valid unix timestamp from $datestring.
I tried several different approaches like strtotime, date_parse_from_format, etc., I even tried to set the locale environment via setlocale. Of course it would be easy to parse the string against an array with the month names and get an english datestring, but I want to have this ready for all languages.
Any Idea how to get this done? Help is really appreciated.
You need to use mktime($datestring)
and set the $datestring variable in accordance to:
http://pl1.php.net/manual/de/function.mktime.php
in wordpress:
mktime(get_the_date("H"), get_the_date("i"), get_the_date("s"), get_the_date("n"), get_the_date("j"), get_the_date("Y"));
if you need to convert exact format shown above:
$datestring = '3. März 2014';
$dateelements = explode(" ", $datestring);
$day = rtrim($dateelements[0], ".");
$germanMonths = array(1 => "Januar", 2 => "Februar", 3 => "März", 4 => "April", 5 => "Mai", 6 => "Juni", 7 => "Juli", 8 => "August", 9 => "September", 10 => "Oktober " , 11 => "November", 12 => "Dezember");
$month = array_search($dateelements[1], $germanMonths);
$year = $dateelements[2];
$unixtimestamp = mktime(0,0,0,$month,$day,$year);
and if you have a date format in wp option, and $datestring is in that format:
$dateformat = get_option('date_format');
echo $dateformat;
$date = date_create_from_format($dateformat, $datestring);
$new_format = date_format($date, 'm,d,Y');
$unixtimestamp = mktime(0,0,0,$new_format);
echo $unixtimestamp;

Dynamic date definition and conditions

I am building a small class combination to calculate the precise date of the beginning of a semester. The rules for determining the beginning of the semester goes as follow :
The monday of week number ## and after dd-mm-yyyy date
ie: for winter its week number 2 and it must be after the january 8th of that year
I am building a resource class that contain these data for all the semesters (4 in total). But now I am facing an issue based on the public holidays. Since some of those might be on a Monday, in those cases I need to get the date of the Tuesday.
The issue I am currently working on is the following :
The target semester begins on or after august 30 and must be on week 35.
I also have to take account of a public holiday which happen on the first monday of september.
The condition in PHP terms is the following
if (date('m', myDate) == 9 // if the month is september
&& date('w', myDate) == 1 // if the day of the week is monday
&& date('d', myDate) < 7 // if we are in the first 7 days of september
)
What would be the best way to "word" this as a condition and store it in an array?
EDIT
I might not have been clear enough, finding the date is not the problem here. The actual problem is storing a condition in a configuration array that looks like the following :
$_ressources = array(
1 => array(
'dateMin' => '08-01-%',
'weekNumber' => 2,
'name' => 'Winter',
'conditions' => array()
),
2 => array(
'dateMin' => '30-04-%',
'weekNumber' => 18,
'name' => 'Spring',
'conditions' => array()
),
3 => array(
'dateMin' => '02-07-%',
'weekNumber' => 27,
'name' => 'Summer',
'conditions' => array()
),
4 => array(
'dateMin' => '30-08-%',
'weekNumber' => 35,
'name' => 'Autumn',
'conditions' => array("date('m', %date%) == 9 && date('w', %date%) == 1 && date('d', %date%) < 7")
)
);
The issue I have with the way it's presented now, is that I will have to use the eval() function, which I would rather not to.
You said:
The target semester begins on or after august 30 and must be on week 35.
If that's the case you can simple check for week number.
if(date('W', myDate) == 35)
Or if your testing condition is correct then you should compare day number till 7 as it starts from 1.
if((date('m', myDate) == 9 // september
&& date('w', myDate) == 1 // monday
&& date('d', myDate) <= 7 // first 7 days of september
)
And then in the if statement, once you have found the monday which would be OK IF its not a public holiday, do this
if(...){
while(!array_search (myDate, aray_of_public_holidays))
date_add($myDate, date_interval_create_from_date_string('1 days'));
}
Here the array_of_public_holidays contains the list of public holidays.
Update with Code
Following code should work for your purposes
<?php
// array with public holidays
$public_holidays = array(/* public holidays */);
// start on 30th august
$myDate = new DateTime('August 30');
// loop till week number does not cross 35
while($myDate->format('W') <= 35){
// if its a monday
if($myDate->format('w') == 1){
// find the next date not a public holiday
while(array_search($myDate, $public_holidays))
$myDate->add(date_interval_create_from_date_string('1 days'));
// now myDate stores the valid semester start date so exit loop
break;
}
// next date
$myDate->add(date_interval_create_from_date_string('1 days'));
}
// now myDate is the semester start date
?>
Update according to updated question
Following code should work for your needs. You do not need to store the condition in your array as PHP code. The following code shows how it can be done
// semester conditions
$sem_conditions = array(
1 => array(
'dateMin' => '08-01-%',
'weekNumber' => 2,
'name' => 'Winter'
),
2 => array(
'dateMin' => '30-04-%',
'weekNumber' => 18,
'name' => 'Spring'
),
3 => array(
'dateMin' => '02-07-%',
'weekNumber' => 27,
'name' => 'Summer'
),
4 => array(
'dateMin' => '30-08-%',
'weekNumber' => 35,
'name' => 'Autumn'
)
);
// array with public holidays format (d-M)
$public_holidays = array('05-09', '10-01');
// store sem starts
$sem_starts = array();
// for each semester
foreach($sem_conditions as $sem){
// start date
$myDate = date_create_from_format('d-m', substr($sem['dateMin'], 0, -2));
// loop till week number does not cross $sem['weekNumber']
while($myDate->format('W') <= $sem['weekNumber']){
// if its a monday
if($myDate->format('w') == 1){
// find the next date not a public holiday
while(array_search($myDate->format('d-m'), $public_holidays) !== false)
$myDate->add(date_interval_create_from_date_string('1 days'));
// now myDate stores the valid semester start date so exit loop
break;
}
// next date
$myDate->add(date_interval_create_from_date_string('1 days'));
}
// add to sem starts
$sem_start[$sem['name']] = $myDate->format('d-m-Y');
}
var_dump($sem_start);
The target semester begins on or after august 30 and must be on week 35
The start of the semester is the minimal date between week 35 and August 30:
$week35 = new DateTime("January 1 + 35 weeks");
$august30 = new DateTime("August 30");
$start = min($week35, $august30);
Alternatively:
$start = min(date_create("January 1 + 52 weeks"), date_create("August 30"));

Categories