duanbi7204
2019-05-08 05:14 阅读 510
已采纳

从时间字符串获取小时和分钟

I have response from an API like below

2019-05-08T10:36:00+0530

I want to take 10:36 from it, right now I do something with regex like

preg_match('/T(.*?)\:00/');

It works, but is there any other actual way to do it more efficiently? That works on any time string in this format?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    doutou19761022 doutou19761022 2019-05-08 05:22

    Create a DateTime object by passing that string into the constructor and just format it to your liking with format()! You might want H:i if you just want the hours and minutes, or H:i:s if you want to include the seconds.

    $string = "2019-05-08T10:36:00+0530";
    $date = new DateTime($string);
    echo $date->format("H:i:s");
    
    点赞 评论 复制链接分享
  • dongxiangqian1855 dongxiangqian1855 2019-05-08 05:25

    If your string format is fixed, you can use substr().

    $string = "2019-05-08T10:36:00+0530";
    echo substr($string, 11, 5);
    

    Output:

    10:36
    

    Working Example:

    点赞 评论 复制链接分享

相关推荐