Get time from a date/time string

Get time from a date/time string

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Extracting and Manipulating Time from Dense Date Strings

Handling date and time strings in PHP often involves a mix of string manipulation and datetime arithmetic. When dealing with compact formats like YmdHis (e.g., 20110805124000), the challenge lies in separating the temporal components to perform specific operations without corrupting the original data structure. The goal here is to extract just the hour and minute, format them as HH:MM, and then adjust that time by a specific number of hours, potentially resulting in values like 15:40.

Parsing the String Format

The input string 20110805124000 represents a dense concatenation of year, month, day, hour, minute, and second. To isolate the time component, you need to slice the string at the correct boundaries. In this specific format, the first four characters represent the date (Ymd) and the next two represent the hours (Hi). The seconds follow immediately after.

You can extract the relevant substrings using PHP's substr function. Since the format is fixed-width, you don't necessarily need complex regex patterns unless the input source varies. For a string starting at index 0 with a length of 14 characters:

  • Indices 0–3 contain the date.
  • Indices 4–5 contain the hour.
  • Indices 6–7 contain the minute.
$fulltime = '20110805124000';

// Extract time substring (characters at index 4 and 5 for hours, 6 and 7 for minutes)
$timePart = substr($fulltime, 4, 2) . ':' . substr($fulltime, 6, 2);

$shorttime = $timePart;

This approach yields 12:40. It is efficient because it avoids parsing the entire date object when you only care about the time portion. However, this method assumes the input string strictly adheres to the YmdHis pattern. If there is any chance of missing data or variable length, relying on string slicing becomes risky.

Performing Arithmetic on Time Strings

Once you have $shorttime, attempting to add hours directly to the string is error-prone. You cannot simply increment the hour substring because crossing midnight requires logic that string manipulation alone cannot handle efficiently. For instance, adding 3 hours to 23:40 should result in 02:40 of the next day, not 26:40.

The robust solution is to treat the time as a timestamp or use DateTime objects for the arithmetic, then format the result back into your desired string. This ensures that date rollovers (like midnight) and leap seconds are handled correctly by the underlying C library functions.

$addtime = 3; // Could be negative

// Create a DateTime object using the original full string
$dateObj = new DateTime($fulltime);

// Add the hours
$dateObj->modify("+{$addtime} hours");

// Re-extract the time part from the modified object
$newShortTime = $dateObj->format('H:i');

Using DateTime::modify is generally preferred over manual math because it automatically handles edge cases. If $addtime is negative, say -5, the code will correctly subtract time and roll back to the previous day if necessary. The final formatting step extracts just the hour and minute in 24-hour notation, ignoring seconds as requested.

Performance Considerations

For high-frequency operations where every millisecond counts, string slicing might seem faster than instantiating DateTime objects. However, modern PHP engines are optimized for these operations, and the readability and correctness benefits of using DateTime often outweigh the minimal performance cost. If you are processing millions of records in a loop, you might consider caching the parsing logic or using integer timestamps throughout the calculation phase, converting to the string representation only at the point of output.

Validation and Safety

If the source of $fulltime is user-controlled or comes from an external API, always validate that it matches the expected YmdHis pattern before slicing. A regex check like /^\d{14}$/ ensures no non-numeric characters slip through, preventing potential parsing errors downstream. This defensive programming step prevents subtle bugs where a malformed string results in incorrect time extraction or application crashes.

By combining precise string slicing for extraction with DateTime objects for arithmetic, you maintain both code clarity and operational correctness.

Our network