سؤال

I am processing some strings in a PHP script which may be in Y-m-d H:i:s or Y-m-d format. I need to remove the H:i:s portion from the datetime strings so that I am consistently dealing with Y-m-d date strings.

How can I remove this trailing string (and its leading space) if it exists?

My strings might look like 2003-11-24 23:52:18 or 2009-01-25.

My expected results from these strings are 2003-11-24 and 2009-01-25.

I do not need to validate that these strings represent real "date" or "datetime" values.

هل كانت مفيدة؟

المحلول

Since the length of the date is always fix. You can use substr.

// With 00:00:00
$date = '2003-01-2800:00:00';
echo substr($date, 0, 10) . '<br>';

// Without 00:00:00
$date = '2003-01-28';
echo substr($date, 0, 10) . '<br>'; 

// With other time part
$date = '2003-01-2812:00:11';
echo substr($date, 0, 10);          

نصائح أخرى

you could use a simple explode or as noted in the comments substr but if you don't know how the string will be formatted a more complex date('Y-m-d', strtotime($mytime)) based on your updated post...

$newdate = substr($olddate,0,10);

Your incoming data is a date string, so treat it as such and use DateTime to manipulate it. Your solution could be as simple as:-

$dateString = (new \DateTime('2003-01-28 00:00:00'))->format('Y-m-d');
//$dateString now === '2003-01-28'

This will work even if the time portion (00:00:00) is missing. and even if there is no space between the date and time.

As you can see this should cover all of your possible inputs.

EDIT #2 (using str_replace)

The position of 00:00:00 doesn't matter in this case, even if the dates have no space between them.

Works on 00:00:00 2003-01-28 and 2003-01-28 00:00:00 and 2003-01-2800:00:00

<?php

$if_date_null = "00:00:00";
 
$replace = ""; // replace with nothing

// doesn't matter the position of 00:00:00
$dates = "00:00:00 2003-01-28";
// $dates = "2003-01-28 00:00:00";
 
$result = str_replace($if_date_null,$replace,$dates);
 
echo $result;

?>

EDIT #1

<?php

$date = "2003-01-28";

$date_null = "00:00:00";

if (strpos($date_null,'00:00:00') !== false) {
    echo '00:00:00 found ';
}

else {

echo "No ZEROS found ";

}


?>

Original answer

This will echo 2003-01-28 and not include the space between 2003-01-28 and 00:00:00

<?php

echo substr("2003-01-28 00:00:00",0,-9);

?>

You can also assign date as a variable like this: (will produce the same result) and use that variable elsewhere if needed.

<?php

$date = "2003-01-28";
echo substr("$date 00:00:00",0,-9);

?>

maybe you can use function "date()" to format the timestamp

<?php
$my_date = "2003-01-28 00:00:00";
$new_date = date("Y-m-d", time($my_date));
var_dump($new_date);

First things first, if you are receiving this input data from an earlier layer that is in your control (such as a sql result set), then you should probably standardize the string format before your php touches it. If this data is born from some kind of sql like COALESCE(my_datetime, my_date) AS datetime_or_date, then you could spare your php having to perform potentially iterated calls on each row of your result set. Within your coalescing process, it will be simple to leverage some functions such as CAST(), DATE(), DATE_FORMAT(), CONVERT(), or STR_TO_DATE() depending on the scenario.

Now, this task seems to have a fairly narrow scope. The input data is either Y-m-d H:i:s or Y-m-d. This is not about validation -- only text extraction. In this case, there are several php techniques that can be trusted (and some that can't be). For researchers that may not have valid date/datetime values or the values might be an empty strings or even null, you should be careful about possible side effects of the function/technique that you use.

Consider the following tables of test strings and techniques, and choose with care: (Demo)

"2003-01-28 01:23:45"
(valid datetime)
"2007-04-04"
(valid date)
substr($datetime, 0, 10) "2003-01-28" "2007-04-04"
explode(' ', $datetime, 2)[0] "2003-01-28" "2007-04-04"
sscanf($datetime, '%s', $sscanf); $sscanf "2003-01-28" "2007-04-04"
preg_replace('/ .+/', '', $datetime) "2003-01-28" "2007-04-04"
(new \DateTime($datetime))->format('Y-m-d') "2003-01-28" "2007-04-04"
date("Y-m-d", strtotime($datetime)) "2003-01-28" "2007-04-04"
strtok($datetime, ' ') "2003-01-28" "2007-04-04"
strstr($datetime . ' ', ' ', true) "2003-01-28" "2003-04-04"
"0000-00-00 00:00:00"
(invalid datetime)
"0000-00-00"
(invalid date)
substr($datetime, 0, 10) "0000-00-00" "0000-00-00"
explode(' ', $datetime, 2)[0] "0000-00-00" "0000-00-00"
sscanf($datetime, '%s', $sscanf); $sscanf "0000-00-00" "0000-00-00"
preg_replace('/ .+/', '', $datetime) "0000-00-00" "0000-00-00"
(new \DateTime($datetime))->format('Y-m-d') "-0001-11-30" "-0001-11-30"
date("Y-m-d", strtotime($datetime)) "-0001-11-30" "-0001-11-30"
strtok($datetime, ' ') "0000-00-00" "0000-00-00"
strstr($datetime . ' ', ' ', true) "0000-00-00" "0000-00-00"
""
(empty string)
null
(null value)
substr($datetime, 0, 10) "" ""
explode(' ', $datetime, 2)[0] "" ""
sscanf($datetime, '%s', $sscanf); $sscanf null null
preg_replace('/ .+/', '', $datetime) "" ""
(new \DateTime($datetime))->format('Y-m-d') "2021-08-21" (current date) "2021-08-21" (current date)
date("Y-m-d", strtotime($datetime)) "1970-01-01" "1970-01-01"
strtok($datetime, ' ') false false
strstr($datetime . ' ', ' ', true) "" ""

Some explicit notes:

  1. substr() is a fine tool for this job and returns a stable value in the above cases.
  2. explode() is stable, but not direct since it needs to create an array in the process.
  3. sscanf() with %s searches for the leading substring until a whitespace character is encountered. This is direct, but some might argue that it is lesser known and unintuitive. Also, it provides a reference variable that may need to be unset() in some situations. This exact technique is ONLY useful for this specific scenario. Depending on how the input string and the delimiter may vary, sscanf() may or may not be viable.
  4. preg_replace() provides a stable result, but it will never win on speed. Frankly, there is no benefit to wheeling out the regex engine when there are non-regex techniques that can do the exact same thing. Not recommended.
  5. format() can provide some unwanted results when an invalid or missing value is provided. I would argue that because this is merely a text-extraction task, there is no need to instantiate a datetime object and call a formatting method. Not recommended.
  6. strtotime() & date() can provide some unwanted results when an invalid or missing value is provided. I don't see any reason to call two functions when the task can be done in one function call. Not recommended.
  7. strtok() might be the most ideal and is the most concise technique when values are guaranteed to have length. However, when the input has no length, be aware of the boolean return value.
  8. strstr() can be used for this task, but to ensure a stable return value, the delimiting character must be unconditionally appended to the string being searched. In other words, the delimiter must be found. This technique just feels unnecessarily hacky, given that other techniques don't need to mutate the input string.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top