Convert uncommon date format to timestamp in most efficient manner possible?

后端 未结 4 431
鱼传尺愫
鱼传尺愫 2020-12-09 04:06

I have a date in this format: 20101101120000

I need to convert it to a timestamp with PHP.

I\'ve been searching the PHP docs online, but can\'t find anything

相关标签:
4条回答
  • 2020-12-09 04:32
    strtotime('20101101120000')
    

    ....

    0 讨论(0)
  • 2020-12-09 04:35

    You can do this with DateTime::createFromFormat:

    $d = DateTime::createFromFormat('YmdGis', '20101101120000');
    

    $d is now a DateTime instance. You can either convert it to a timestamp with $d->getTimestamp() or use the DateTime methods on it.

    Note that this requires PHP 5.3.

    0 讨论(0)
  • 2020-12-09 04:45

    I only add to this resolved question because this may be helpful for users who stumble upon here (like I did) and are looking to get an actual datetime timestamp.

    My assumption for most folks when they mention timestamp is that they're looking for a normal "YYYY-MM-DD HH:MM:SS" timestamp not a unix timestamp which you get when you use the getTimestamp() method (see accepted answer if you are indeed looking for the UNIX Timestamp).

    So I will further elaborate on lonesomeday's answer (which is fully correct) for those looking to actually get a valid formated date that they can display to users or insert into their database:

    $d = DateTime::createFromFormat('YmdGis', '20101101120000');
    
    $formatedDate = $d->format('Y-m-d H:i:s'); // will return 2010-11-01 12:00:00
    $formatedDate = $d->format('m-d-Y h:i A'); // will return 11-01-2010 12:00 PM 
    
    0 讨论(0)
  • 2020-12-09 04:53

    You need the function strptime.

    The formats are described at strftime.

    0 讨论(0)
提交回复
热议问题