phpregexdatetimetext-parsingdate-parsing

Parse datetime string in Ydm.His format


I've a string like below

$num = "20142311.235504";

I want to split the string in below format

$date['year'] = 2014;
$date['Month'] = 23;
$date['day'] = 11;
$date['hour'] = 23;
$date['min'] = 55;
$date['sec'] = 04;

or even in date form like below

2014/23/11 23:55:04

I tried using preg_split('/(d{4})/',$num,$matches); and str_split but am not getting the desired output.


Solution

  • If the string is a date, you can do this :

    $num = "20142311.235504";
    
    // You create a date with your string according to your current format
    $date = date_create_from_format("Ydm.His", $num);
    
    // Now you can play with it
    $formattedDate = $date->format("Y/d/m H:i:s"); // `string(19) "2014/23/11 23:55:04"` 
    
    $dateTest['year']  = $date->format("Y"); // 2014
    $dateTest['Month'] = $date->format("m"); // 11
    $dateTest['day']   = $date->format("d"); // 23
    $dateTest['hour']  = $date->format("H"); // 23
    $dateTest['min']   = $date->format("i"); // 55
    $dateTest['sec']   = $date->format("s"); // 04
    
    

    Demo here : http://sandbox.onlinephpfunctions.com/