Retrieve date format and parse if needed in PHP - php

I've created this function when retrieving a date from database and echo in Italian format to screen:
function get_data_ita($date) {
if ($date == "")
return "";
$d = new DateTime($date);
return $d->format('d/m/Y');
}
where $date is mysql format like: 2017-12-31 14:00:00
Now, if I pass a correct format like: 2017-12-31 14:00:00 the function works.
But sometimes I need to use the SAME function, passing an already formatted date like: 30/12/2017. In this case, i get parsing error of course.
How can I check if date passed is already in Italian format, and if yes return the untouched date, if not, parse the date?
I need a function like:
function get_data_ita($date) {
if ( $date== ALREADY_IN_ITALIAN_FORMAT )
return $date;
if ($date == "")
return "";
$d = new DateTime($date);
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo get_data_ita("2017-12-31 14:00:00");
ECHO:
30/12/2017
31/12/2017
UPDATE: I found solution myself:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function get_data_ita($datetime_db) {
if ( validateDate($datetime_db, 'd/m/Y') ) {
return $datetime_db;
}
if ($datetime_db == "")
return "";
$date = new DateTime($datetime_db);
return $date->format('d/m/Y');
}

Replace / to -
<?php
function get_data_ita($date) {
if ($date == ""){
return "";
}
$date = str_replace('/','-',$date);
$d = new DateTime($date);
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo "\n";
echo get_data_ita("2017-12-31 14:00:00");
?>
Check demo : https://eval.in/918149

Strtotime returns false if the date is not a valid date format.
This works for your inputs but not if there are other date formats.
function get_data_ita($date) {
if ($date == "") return "";
If(strtotime($date) !== False){
$d = new DateTime($date);
}Else{
$d = DateTime::createFromFormat('d/m/Y', $date);
}
return $d->format('d/m/Y');
}
echo get_data_ita("30/12/2017");
echo get_data_ita("2017-12-31 14:00:00");
https://3v4l.org/kt5Vg

Related

check the date format that is it correct or not

i want to check the date format of the database value. I want to put a check in my code if the format of the date string is correct. If it is not correct then store the empty value.
$getTmpAfSite = DB::table('tmp_af_site')->orderBy('id','DESC')->get(['id','name','email','number','origin','destination','estimated_rate','make','model','year','running_condition','carrier_type','avail_date','lead_source','request_params','bats_id','submitted_on']);
foreach ($getTmpAfSite as $key => $value) {
$avail_date = ($value->avail_date != '' && $value->avail_date == Carbon::parse($value->submitted_on)->format('m/d/Y')) ? Carbon::createFromFormat('m/d/Y', $value->avail_date)->format('Y-m-d') : '0000-00-00';
$submitted_on = ($value->submitted_on != '' && $value->submitted_on == Carbon::parse($value->submitted_on)->format('m/d/Y H:i')) ? Carbon::createFromFormat('m/d/Y H:i', $value->submitted_on)->format('Y-m-d H:i') : '0000-00-00 00:00:00';
DB::table('tmp_af_site')->where('id', $value->id)->update([
'avail_date'=>$avail_date,
'submitted_on'=>$submitted_on
]);
}
i am trying this code to check the value but its not working for me. If i didn't put a check on it and the wrong format comes then the error happens. Here is the error
Unexpected data found. Data missing
try use this function, this function check valid or not valid string date with return true false
function validateDate($date, $format = 'd-M-Y')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
}
if you want more format date, you can add checking date like this
function validateDate($date)
{
$valid = 0;
$format1 = 'Y-m-d';
$d = DateTime::createFromFormat($format1, $date);
if($d && $d->format($format) === $date){
$valid = 1;
}
$format2 = 'd-m-Y';
$d = DateTime::createFromFormat($format2, $date);
if($d && $d->format($format2) === $date){
$valid = 1;
}
return $valid;
}
You can use :
checkdate(int $month, int $day, int $year): bool
Example :
<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
#bool(true)
#bool(false)
$valid = checkdate(12,31,2000);
if ($valid)
echo "Date is valid.";
else
echo "Date is not valid.";
?>
Regards,

Check if 2 given dates are a weekend using PHP

I have 2 dates like this YYYY-mm-dd and I would like to check if these 2 dates are a weekend.
I have this code but it only tests 1 date and I don't know how to adapt it; I need to add a $date_end.
$date = '2011-01-01';
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
echo "true";
} else {
echo "false";
}
A couple of hints:
date('N') gives you normalised week day you can test against (no need to use localised strings)
Wrap it all in a custom function and you're done
You can use shorter code to check for weekend => date('N', strtotime($date)) >= 6.
So, to check for 2 dates — and not just 1 — use a function to keep your code simple and clean:
$date1 = '2011-01-01' ;
$date2 = '2017-05-26';
if ( check_if_weekend($date1) && check_if_weekend($date2) ) {
echo 'yes. both are weekends' ;
} else if ( check_if_weekend($date1) || check_if_weekend($date2) ) {
echo 'no. only one date is a weekend.' ;
} else {
echo 'no. neither are weekends.' ;
}
function check_if_weekend($date) {
return (date('N', strtotime($date)) >= 6);
}
Using your existing code, which is slightly longer, following is how you would check for 2 dates:
$date1 = '2011-01-01' ;
$date2 = '2017-05-27';
if ( check_if_weekend_long($date1) && check_if_weekend_long($date2) ) {
echo 'yes. both are weekends' ;
} else if ( check_if_weekend_long($date1) || check_if_weekend_long($date2) ) {
echo 'no. only one date is a weekend.' ;
} else {
echo 'no. neither are weekends.' ;
}
function check_if_weekend_long($date_str) {
$timestamp = strtotime($date_str);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
//echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
return true;
} else {
return false;
}
}
Merging multiple answers into one and giving a bit extra, you'd come to the following:
function isWeekend($date) {
return (new DateTime($date))->format("N") > 5 ? true : false;
}
Or the long way:
function isWeekend($date) {
if ((new DateTime($date))->format("N") > 5) {
return true;
}
return false;
}
You can use the strtotime(); and date() functions to get the day of the date, and then check if is sat o sun
function check_if_weekend($date){
$timestamp = strtotime($date);
$day = date('D', $timestamp);
if(in_array($day, array('sun', 'sat'))
return true;
else return false;
}

Find out whether string has date in it

I have a string "scbdemo2016-10-21:getlastweekReadBooks4795".
How to find out the above string has date in it and to validate the date is current day date.
Easily done with regular expressions:
$isToday = stringDateToday("scbdemo2016-10-21:getlastweekReadBooks4795");
function stringDateToday($string) {
$reg = "/\d{4}-\d{2}-\d{2}/";
$date = new DateTime();
preg_match($reg, $string, $matches);
if (isset($matches[0])) {
return $matches[0] == $date->format("Y-m-d");
}
return false;
}
stringDateToday() will return true if the date in the string is today. The date can be anywhere in the string.
EDIT:
As suggested in the comments, you may want to change new DateTime() to new DateTime('now', new DateTimeZone('Europe/London')) to specify timezone.
Here is your code, but it only works with string that has : character, anyways
function checkdata($date, $format)
{
$format=strstr(preg_replace("/[a-zA-Z]+/", '',$format),":",true);
// date_default_timezone_set('UTC');
$d = DateTime::createFromFormat($format, $date);
if($d && $d->format($format) === $date) {
return true;
} else {
return false;
}
}
$data="scbdemo2016-10-21:getlastweekReadBooks4795";
if(checkdata($data,'Y-m-d'))
echo "Yes";
else
echo "NO";

unable to validate date

i am trying to validate date which is in between 1996 & 1900 for date of birth field. And also it should be in correct date format
but this below function is giving me output always false.
what i am doing wrong ?
function validateDate($date) {
$this->load->helper('date');
$datestring1 = "%Y-%m-%d";
$date1 = "1996-01-01";
$date2 = "1990-01-01";
$d = DateTime::createFromFormat('Y-m-d', $date);
return $d && $d->format('Y-m-d') == $date && $date > $date2 && $date < $date1;
}
I don't know what is wrong with your function but this should work
function validate($date){
$d = DateTime::createFromFormat('Y-m-d', $date);
if($d === false) return false;
$y = intval($d->format('Y'));
return $y >= 1990 && $y < 1996;
}
If you want 1988-07-25 to be a valid entry (as shown in your screenshot), your "date2" should be "1980" or something earlier instead of "1990".
You can try this
function validation($date){ //yyyy-mm-dd
$date_element = explode('-', $date);
if(is_array($date_element) and isset($date_element[0]) and ($date_element[0] >= 1990 and $date_element[0] <= 1996)){
return true;
}
return false;
}

Timezone conversion in PHP with DateTime

I found some solutions recently and decided to go with this one so I created following method within one of my classes:
public static function date($format, $time = false, $from_timezone = false, $to_timezone = false) {
if (!$time) {
$time = time();
}
if (($from_timezone === $to_timezone) || (!$from_timezone || !$to_timezone)) {
return date($format, $time);
}
$from_tz = new DateTimeZone($from_timezone);
$to_tz = new DateTimeZone($to_timezone);
$dt = new DateTime();
$dt->setTimezone($from_tz);
$dt->setTimestamp($time);
$offset = $to_tz->getOffset($dt);
return date($format, $dt->format('U') + $offset);
}
Then I did a simple test - I converted datetime to some other timezone, and then convert the result back to the original timezone with expectations to get the original datetime.
$format = 'Y-m-d H:i:s';
$initialtime = '2013-06-13 12:00:00';
echo $initialtime;
echo '<br/>';
$convtime = TimezoneLib::date($format, strtotime($initialtime), 'Canada/Atlantic', 'Europe/Prague');
echo $convtime;
echo '<br/>';
echo TimezoneLib::date($format, strtotime($convtime), 'Europe/Prague', 'Canada/Atlantic');
die();
This is the output
2013-06-13 12:00:00 // Original
2013-06-13 14:00:00 // Converted
2013-06-13 11:00:00 // Converted to original timezone
Why dont they match? What am I missing? Thank you.
UPDATE
I am still unable to get matching dates even after removing strtotime. I found out that default timezone also affected DateTime objects. I came up with this:
<?php
class TimezoneLib {
public static $defaultSystemTimezone;
public static function init() {
self::$defaultSystemTimezone = date_default_timezone_get();
}
public static function date($format, $time = false, $from_timezone = false, $to_timezone = false) {
self::switchSystemTimezone($from_timezone);
if (!$time) {
$time = time();
}
if (($from_timezone === $to_timezone) || (!$from_timezone || !$to_timezone)) {
return date($format, $time);
}
$from_tz = new DateTimeZone($from_timezone);
$to_tz = new DateTimeZone($to_timezone);
$dt = new DateTime($time, $from_tz);
self::switchSystemTimezone($to_timezone);
$offset = $to_tz->getOffset($dt);
$convertedDate = date($format, $dt->format('U') + $offset);
self::restoreSystemTimezone();
return $convertedDate;
}
public static function switchSystemTimezone($timezone_identifier) {
return date_default_timezone_set($timezone_identifier);
}
public static function restoreSystemTimezone() {
return date_default_timezone_set(self::$defaultSystemTimezone);
}
}
TimezoneLib::init();
$format = 'Y-m-d H:i:s';
$initialtime = '2013-06-13 12:00:00';
echo $initialtime;
echo '<br/>';
$convtime = TimezoneLib::date($format, $initialtime, 'Canada/Atlantic', 'Europe/Prague');
echo $convtime;
echo '<br/>';
echo TimezoneLib::date($format, $convtime, 'Europe/Prague', 'Canada/Atlantic');
die();
With following output
2013-06-13 12:00:00
2013-06-13 19:00:00
2013-06-13 11:00:00
Create a new DateTime object instead than using strtotime:
$date = new DateTime('your_date_here', DateTimeZone object here);

Categories